diff --git "a/swift/containerization_function_bench.jsonl" "b/swift/containerization_function_bench.jsonl" new file mode 100644--- /dev/null +++ "b/swift/containerization_function_bench.jsonl" @@ -0,0 +1,4 @@ +{"repo_name": "containerization", "file_name": "/containerization/Sources/cctl/RunCommand.swift", "inference_info": {"prefix_code": "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\n\nextension Application {\n struct Run: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"run\",\n abstract: \"Run a container\"\n )\n\n @Option(name: [.customLong(\"image\"), .customShort(\"i\")], help: \"Image reference to base the container on\")\n var imageReference: String = \"docker.io/library/alpine:3.16\"\n\n @Option(name: .long, help: \"id for the container\")\n var id: String = \"cctl\"\n\n @Option(name: [.customLong(\"cpus\"), .customShort(\"c\")], help: \"Number of CPUs to allocate to the container\")\n var cpus: Int = 2\n\n @Option(name: [.customLong(\"memory\"), .customShort(\"m\")], help: \"Amount of memory in megabytes\")\n var memory: UInt64 = 1024\n\n @Option(name: .customLong(\"fs-size\"), help: \"The size to create the block filesystem as\")\n var fsSizeInMB: UInt64 = 2048\n\n @Option(name: .customLong(\"mount\"), help: \"Directory to share into the container (Example: /foo:/bar)\")\n var mounts: [String] = []\n\n @Option(name: .long, help: \"IP address with subnet\")\n var ip: String?\n\n @Option(name: .long, help: \"Gateway address\")\n var gateway: String?\n\n @Option(name: .customLong(\"ns\"), help: \"Nameserver addresses\")\n var nameservers: [String] = []\n\n @Option(\n name: [.customLong(\"kernel\"), .customShort(\"k\")], help: \"Kernel binary path\", completion: .file(),\n transform: { str in\n URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)\n })\n public var kernel: String\n\n @Option(name: .long, help: \"Current working directory\")\n var cwd: String = \"/\"\n\n @Argument var arguments: [String] = [\"/bin/sh\"]\n\n ", "suffix_code": "\n\n private static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.containerization\")\n }()\n }\n}\n", "middle_code": "func run() async throws {\n let kernel = Kernel(\n path: URL(fileURLWithPath: kernel),\n platform: .linuxArm\n )\n let manager = try await ContainerManager(\n kernel: kernel,\n initfsReference: \"vminit:latest\",\n )\n let sigwinchStream = AsyncSignalHandler.create(notify: [SIGWINCH])\n let current = try Terminal.current\n try current.setraw()\n defer { current.tryReset() }\n let container = try await manager.create(\n id,\n reference: imageReference,\n rootfsSizeInBytes: fsSizeInMB.mib()\n ) { config in\n config.cpus = cpus\n config.memoryInBytes = memory.mib()\n config.process.setTerminalIO(terminal: current)\n config.process.arguments = arguments\n config.process.workingDirectory = cwd\n for mount in self.mounts {\n let paths = mount.split(separator: \":\")\n if paths.count != 2 {\n throw ContainerizationError(\n .invalidArgument,\n message: \"incorrect mount format detected: \\(mount)\"\n )\n }\n let host = String(paths[0])\n let guest = String(paths[1])\n let czMount = Containerization.Mount.share(\n source: host,\n destination: guest\n )\n config.mounts.append(czMount)\n }\n var hosts = Hosts.default\n if let ip {\n guard let gateway else {\n throw ContainerizationError(.invalidArgument, message: \"gateway must be specified\")\n }\n config.interfaces.append(NATInterface(address: ip, gateway: gateway))\n config.dns = .init(nameservers: [gateway])\n if nameservers.count > 0 {\n config.dns = .init(nameservers: nameservers)\n }\n hosts.entries.append(\n Hosts.Entry(\n ipAddress: ip,\n hostnames: [id]\n ))\n }\n config.hosts = hosts\n }\n defer {\n try? manager.delete(id)\n }\n try await container.create()\n try await container.start()\n try? await container.resize(to: try current.size)\n try await withThrowingTaskGroup(of: Void.self) { group in\n group.addTask {\n for await _ in sigwinchStream.signals {\n try await container.resize(to: try current.size)\n }\n }\n try await container.wait()\n group.cancelAll()\n try await container.stop()\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "swift", "sub_task_type": null}, "context_code": [["/containerization/Sources/cctl/ImageCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\nextension Application {\n struct Images: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"images\",\n abstract: \"Manage images\",\n subcommands: [\n Get.self,\n Delete.self,\n Pull.self,\n Tag.self,\n Push.self,\n Save.self,\n Load.self,\n ]\n )\n\n func run() async throws {\n let store = Application.imageStore\n let images = try await store.list()\n\n print(\"REFERENCE\\tMEDIA TYPE\\tDIGEST\")\n for image in images {\n print(\"\\(image.reference)\\t\\(image.mediaType)\\t\\(image.digest)\")\n }\n }\n\n struct Delete: AsyncParsableCommand {\n @Argument var reference: String\n\n func run() async throws {\n let store = Application.imageStore\n try await store.delete(reference: reference)\n }\n }\n\n struct Tag: AsyncParsableCommand {\n @Argument var old: String\n @Argument var new: String\n\n func run() async throws {\n let store = Application.imageStore\n _ = try await store.tag(existing: old, new: new)\n }\n }\n\n struct Get: AsyncParsableCommand {\n @Argument var reference: String\n\n func run() async throws {\n let store = Application.imageStore\n let image = try await store.get(reference: reference)\n\n let index = try await image.index()\n\n let enc = JSONEncoder()\n enc.outputFormatting = .prettyPrinted\n let data = try enc.encode(ImageDisplay(reference: image.reference, index: index))\n print(String(data: data, encoding: .utf8)!)\n }\n }\n\n struct ImageDisplay: Codable {\n let reference: String\n let index: Index\n }\n\n struct Pull: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"pull\",\n abstract: \"Pull an image's contents into a content store\"\n )\n\n @Argument var ref: String\n\n @Option(name: .customLong(\"platform\"), help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platformString: String?\n\n @Option(\n name: .customLong(\"unpack-path\"), help: \"Path to a new directory to unpack the image into\",\n transform: { str in\n URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)\n })\n var unpackPath: String?\n\n @Flag(help: \"Pull via plain text http\") var http: Bool = false\n\n func run() async throws {\n let imageStore = Application.imageStore\n let platform: Platform? = try {\n if let platformString {\n return try Platform(from: platformString)\n }\n return nil\n }()\n\n let reference = try Reference.parse(ref)\n reference.normalize()\n let normalizedReference = reference.description\n if normalizedReference != ref {\n print(\"Reference resolved to \\(reference.description)\")\n }\n\n let image = try await Images.withAuthentication(ref: normalizedReference) { auth in\n try await imageStore.pull(reference: normalizedReference, platform: platform, insecure: http, auth: auth)\n }\n\n guard let image else {\n print(\"image pull failed\")\n Application.exit(withError: POSIXError(.EACCES))\n }\n\n print(\"image pulled\")\n guard let unpackPath else {\n return\n }\n guard !FileManager.default.fileExists(atPath: unpackPath) else {\n throw ContainerizationError(.exists, message: \"Directory already exists at \\(unpackPath)\")\n }\n let unpackUrl = URL(filePath: unpackPath)\n try FileManager.default.createDirectory(at: unpackUrl, withIntermediateDirectories: true)\n\n let unpacker = EXT4Unpacker.init(blockSizeInBytes: 2.gib())\n\n if let platform {\n let name = platform.description.replacingOccurrences(of: \"/\", with: \"-\")\n let _ = try await unpacker.unpack(image, for: platform, at: unpackUrl.appending(component: name))\n } else {\n for descriptor in try await image.index().manifests {\n if let referenceType = descriptor.annotations?[\"vnd.docker.reference.type\"], referenceType == \"attestation-manifest\" {\n continue\n }\n guard let descPlatform = descriptor.platform else {\n continue\n }\n let name = descPlatform.description.replacingOccurrences(of: \"/\", with: \"-\")\n let _ = try await unpacker.unpack(image, for: descPlatform, at: unpackUrl.appending(component: name))\n print(\"created snapshot for platform \\(descPlatform.description)\")\n }\n }\n }\n }\n\n struct Push: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"push\",\n abstract: \"Push an image to a remote registry\"\n )\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platformString: String?\n\n @Flag(help: \"Push via plain text http\") var http: Bool = false\n\n @Argument var ref: String\n\n func run() async throws {\n let imageStore = Application.imageStore\n let platform: Platform? = try {\n if let platformString {\n return try Platform(from: platformString)\n }\n return nil\n }()\n\n let reference = try Reference.parse(ref)\n reference.normalize()\n let normalizedReference = reference.description\n if normalizedReference != ref {\n print(\"Reference resolved to \\(reference.description)\")\n }\n\n try await Images.withAuthentication(ref: normalizedReference) { auth in\n try await imageStore.push(reference: normalizedReference, platform: platform, insecure: http, auth: auth)\n }\n print(\"image pushed\")\n }\n }\n\n struct Save: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"save\",\n abstract: \"Save one or more images to a tar archive\"\n )\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platform: String?\n\n @Option(name: .shortAndLong, help: \"Path to tar archive\")\n var output: String\n\n @Argument var reference: [String]\n\n func run() async throws {\n var p: Platform? = nil\n if let platform {\n p = try Platform(from: platform)\n }\n let store = Application.imageStore\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n try await store.save(references: reference, out: tempDir, platform: p)\n let writer = try ArchiveWriter(format: .pax, filter: .none, file: URL(filePath: output))\n try writer.archiveDirectory(tempDir)\n try writer.finishEncoding()\n print(\"image exported\")\n }\n }\n\n struct Load: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"load\",\n abstract: \"Load one or more images from a tar archive\"\n )\n\n @Option(name: .shortAndLong, help: \"Path to tar archive\")\n var input: String\n\n func run() async throws {\n let store = Application.imageStore\n let tarFile = URL(fileURLWithPath: input)\n let reader = try ArchiveReader(file: tarFile.absoluteURL)\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n try reader.extractContents(to: tempDir)\n let imported = try await store.load(from: tempDir)\n for image in imported {\n print(\"imported \\(image.reference)\")\n }\n }\n }\n\n private static func withAuthentication(\n ref: String, _ body: @Sendable @escaping (_ auth: Authentication?) async throws -> T?\n ) async throws -> T? {\n var authentication: Authentication?\n let ref = try Reference.parse(ref)\n guard let host = ref.resolvedDomain else {\n throw ContainerizationError(.invalidArgument, message: \"No host specified in image reference\")\n }\n authentication = Self.authenticationFromEnv(host: host)\n if let authentication {\n return try await body(authentication)\n }\n let keychain = KeychainHelper(id: Application.keychainID)\n authentication = try? keychain.lookup(domain: host)\n return try await body(authentication)\n }\n\n private static func authenticationFromEnv(host: String) -> Authentication? {\n let env = ProcessInfo.processInfo.environment\n guard env[\"REGISTRY_HOST\"] == host else {\n return nil\n }\n guard let user = env[\"REGISTRY_USERNAME\"], let password = env[\"REGISTRY_TOKEN\"] else {\n return nil\n }\n return BasicAuthentication(username: user, password: password)\n }\n }\n}\n"], ["/containerization/Sources/Integration/Suite.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport NIOCore\n\nlet log = {\n LoggingSystem.bootstrap(StreamLogHandler.standardError)\n var log = Logger(label: \"com.apple.containerization\")\n log.logLevel = .debug\n return log\n}()\n\nenum IntegrationError: Swift.Error {\n case assert(msg: String)\n case noOutput\n}\n\nstruct SkipTest: Swift.Error, CustomStringConvertible {\n let reason: String\n\n var description: String {\n reason\n }\n}\n\n@main\nstruct IntegrationSuite: AsyncParsableCommand {\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.containerization\")\n }()\n\n private static let _contentStore: ContentStore = {\n try! LocalContentStore(path: appRoot.appending(path: \"content\"))\n }()\n\n private static let _imageStore: ImageStore = {\n try! ImageStore(\n path: appRoot,\n contentStore: contentStore\n )\n }()\n\n static let _testDir: URL = {\n FileManager.default.uniqueTemporaryDirectory(create: true)\n }()\n\n static var testDir: URL {\n _testDir\n }\n\n static var imageStore: ImageStore {\n _imageStore\n }\n\n static var contentStore: ContentStore {\n _contentStore\n }\n\n static let initImage = \"vminit:latest\"\n\n @Option(name: .shortAndLong, help: \"Path to a log file\")\n var bootlog: String\n\n @Option(name: .shortAndLong, help: \"Path to a kernel binary\")\n var kernel: String = \"./bin/vmlinux\"\n\n static func binPath(name: String) -> URL {\n URL(fileURLWithPath: FileManager.default.currentDirectoryPath)\n .appendingPathComponent(\"bin\")\n .appendingPathComponent(name)\n }\n\n func bootstrap() async throws -> (rootfs: Containerization.Mount, vmm: VirtualMachineManager, image: Containerization.Image) {\n let reference = \"ghcr.io/linuxcontainers/alpine:3.20\"\n let store = Self.imageStore\n\n let initImage = try await store.getInitImage(reference: Self.initImage)\n let initfs = try await {\n let p = Self.binPath(name: \"init.block\")\n do {\n return try await initImage.initBlock(at: p, for: .linuxArm)\n } catch let err as ContainerizationError {\n guard err.code == .exists else {\n throw err\n }\n return .block(\n format: \"ext4\",\n source: p.absolutePath(),\n destination: \"/\",\n options: [\"ro\"]\n )\n }\n }()\n\n var testKernel = Kernel(path: .init(filePath: kernel), platform: .linuxArm)\n testKernel.commandLine.addDebug()\n let image = try await Self.fetchImage(reference: reference, store: store)\n let platform = Platform(arch: \"arm64\", os: \"linux\", variant: \"v8\")\n\n let fs: Containerization.Mount = try await {\n let fsPath = Self.testDir.appending(component: \"rootfs.ext4\")\n do {\n let unpacker = EXT4Unpacker(blockSizeInBytes: 2.gib())\n return try await unpacker.unpack(image, for: platform, at: fsPath)\n } catch let err as ContainerizationError {\n if err.code == .exists {\n return .block(\n format: \"ext4\",\n source: fsPath.absolutePath(),\n destination: \"/\",\n options: []\n )\n }\n throw err\n }\n }()\n\n let clPath = Self.testDir.appending(component: \"rn.ext4\").absolutePath()\n try? FileManager.default.removeItem(atPath: clPath)\n\n let cl = try fs.clone(to: clPath)\n return (\n cl,\n VZVirtualMachineManager(\n kernel: testKernel,\n initialFilesystem: initfs,\n bootlog: bootlog\n ),\n image\n )\n }\n\n static func fetchImage(reference: String, store: ImageStore) async throws -> Containerization.Image {\n do {\n return try await store.get(reference: reference)\n } catch let error as ContainerizationError {\n if error.code == .notFound {\n return try await store.pull(reference: reference)\n }\n throw error\n }\n }\n\n static func adjustLimits() throws {\n var limits = rlimit()\n guard getrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n limits.rlim_cur = 65536\n limits.rlim_max = 65536\n\n guard setrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n }\n\n // Why does this exist?\n //\n // We need the virtualization entitlement to execute these tests.\n // There currently does not exist a straightforward way to do this\n // in a pure swift package.\n //\n // In order to not have a dependency on xcode, we create an executable\n // for our integration tests that can be signed then ran.\n //\n // We also can't import Testing as it expects to be run from a runner.\n // Hopefully this improves over time.\n func run() async throws {\n try Self.adjustLimits()\n let suiteStarted = CFAbsoluteTimeGetCurrent()\n log.info(\"starting integration suite\\n\")\n\n let tests: [String: () async throws -> Void] = [\n \"process true\": testProcessTrue,\n \"process false\": testProcessFalse,\n \"process echo hi\": testProcessEchoHi,\n \"process user\": testProcessUser,\n \"process stdin\": testProcessStdin,\n \"process home envvar\": testProcessHomeEnvvar,\n \"process custom home envvar\": testProcessCustomHomeEnvvar,\n \"process tty ensure TERM\": testProcessTtyEnvvar,\n \"multiple concurrent processes\": testMultipleConcurrentProcesses,\n \"multiple concurrent processes with output stress\": testMultipleConcurrentProcessesOutputStress,\n \"container hostname\": testHostname,\n \"container hosts\": testHostsFile,\n \"container mount\": testMounts,\n \"nested virt\": testNestedVirtualizationEnabled,\n \"container manager\": testContainerManagerCreate,\n ]\n\n var passed = 0\n var skipped = 0\n for (name, test) in tests {\n do {\n log.info(\"test \\(name) started...\")\n\n let started = CFAbsoluteTimeGetCurrent()\n try await test()\n let lasted = CFAbsoluteTimeGetCurrent() - started\n log.info(\"✅ test \\(name) complete in \\(lasted)s.\")\n passed += 1\n } catch let err as SkipTest {\n log.info(\"⏭️ skipped test: \\(err)\")\n skipped += 1\n } catch {\n log.error(\"❌ test \\(name) failed: \\(error)\")\n }\n }\n\n let ended = CFAbsoluteTimeGetCurrent() - suiteStarted\n var finishingText = \"\\n\\nIntegration suite completed in \\(ended)s with \\(passed)/\\(tests.count) passed\"\n if skipped > 0 {\n finishingText += \" and \\(skipped)/\\(tests.count) skipped\"\n }\n finishingText += \"!\"\n\n log.info(\"\\(finishingText)\")\n\n if passed + skipped < tests.count {\n log.error(\"❌\")\n throw ExitCode(1)\n }\n try? FileManager.default.removeItem(at: Self.testDir)\n }\n}\n"], ["/containerization/Sources/Containerization/ContainerManager.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport ContainerizationExtras\nimport Virtualization\nimport vmnet\n\n/// A manager for creating and running containers.\n/// Supports container networking options.\npublic struct ContainerManager: Sendable {\n public let imageStore: ImageStore\n private let vmm: VirtualMachineManager\n private let network: Network?\n\n private var containerRoot: URL {\n self.imageStore.path.appendingPathComponent(\"containers\")\n }\n\n /// A network that can allocate and release interfaces for use with containers.\n public protocol Network: Sendable {\n func create(_ id: String) throws -> Interface?\n func release(_ id: String) throws\n }\n\n /// A network backed by vmnet on macOS.\n @available(macOS 26.0, *)\n public struct VmnetNetwork: Network {\n private let allocator: Allocator\n nonisolated(unsafe) private let reference: vmnet_network_ref\n\n /// The IPv4 subnet of this network.\n public let subnet: CIDRAddress\n\n /// The gateway address of this network.\n public var gateway: IPv4Address {\n subnet.gateway\n }\n\n struct Allocator: Sendable {\n private let addressAllocator: any AddressAllocator\n private let cidr: CIDRAddress\n private var allocations: [String: UInt32]\n\n init(cidr: CIDRAddress) throws {\n self.cidr = cidr\n self.allocations = .init()\n let size = Int(cidr.upper.value - cidr.lower.value - 3)\n self.addressAllocator = try UInt32.rotatingAllocator(\n lower: cidr.lower.value + 2,\n size: UInt32(size)\n )\n }\n\n func allocate(_ id: String) throws -> String {\n if allocations[id] != nil {\n throw ContainerizationError(.exists, message: \"allocation with id \\(id) already exists\")\n }\n let index = try addressAllocator.allocate()\n let ip = IPv4Address(fromValue: index)\n return try CIDRAddress(ip, prefixLength: cidr.prefixLength).description\n }\n\n func release(_ id: String) throws {\n if let index = self.allocations[id] {\n try addressAllocator.release(index)\n }\n }\n }\n\n /// A network interface supporting the vmnet_network_ref.\n public struct Interface: Containerization.Interface, VZInterface, Sendable {\n public let address: String\n public let gateway: String?\n public let macAddress: String?\n\n nonisolated(unsafe) private let reference: vmnet_network_ref\n\n public init(\n reference: vmnet_network_ref,\n address: String,\n gateway: String,\n macAddress: String? = nil\n ) {\n self.address = address\n self.gateway = gateway\n self.macAddress = macAddress\n self.reference = reference\n }\n\n /// Returns the underlying `VZVirtioNetworkDeviceConfiguration`.\n public func device() throws -> VZVirtioNetworkDeviceConfiguration {\n let config = VZVirtioNetworkDeviceConfiguration()\n if let macAddress = self.macAddress {\n guard let mac = VZMACAddress(string: macAddress) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid mac address \\(macAddress)\")\n }\n config.macAddress = mac\n }\n config.attachment = VZVmnetNetworkDeviceAttachment(network: self.reference)\n return config\n }\n }\n\n /// Creates a new network.\n /// - Parameter subnet: The subnet to use for this network.\n public init(subnet: String? = nil) throws {\n var status: vmnet_return_t = .VMNET_FAILURE\n guard let config = vmnet_network_configuration_create(.VMNET_SHARED_MODE, &status) else {\n throw ContainerizationError(.unsupported, message: \"failed to create vmnet config with status \\(status)\")\n }\n\n vmnet_network_configuration_disable_dhcp(config)\n\n if let subnet {\n try Self.configureSubnet(config, subnet: try CIDRAddress(subnet))\n }\n\n guard let ref = vmnet_network_create(config, &status), status == .VMNET_SUCCESS else {\n throw ContainerizationError(.unsupported, message: \"failed to create vmnet network with status \\(status)\")\n }\n\n let cidr = try Self.getSubnet(ref)\n\n self.allocator = try .init(cidr: cidr)\n self.subnet = cidr\n self.reference = ref\n }\n\n /// Returns a new interface for use with a container.\n /// - Parameter id: The container ID.\n public func create(_ id: String) throws -> Containerization.Interface? {\n let address = try allocator.allocate(id)\n return Self.Interface(\n reference: self.reference,\n address: address,\n gateway: self.gateway.description,\n )\n }\n\n /// Performs cleanup of an interface.\n /// - Parameter id: The container ID.\n public func release(_ id: String) throws {\n try allocator.release(id)\n }\n\n private static func getSubnet(_ ref: vmnet_network_ref) throws -> CIDRAddress {\n var subnet = in_addr()\n var mask = in_addr()\n vmnet_network_get_ipv4_subnet(ref, &subnet, &mask)\n\n let sa = UInt32(bigEndian: subnet.s_addr)\n let mv = UInt32(bigEndian: mask.s_addr)\n\n let lower = IPv4Address(fromValue: sa & mv)\n let upper = IPv4Address(fromValue: lower.value + ~mv)\n\n return try CIDRAddress(lower: lower, upper: upper)\n }\n\n private static func configureSubnet(_ config: vmnet_network_configuration_ref, subnet: CIDRAddress) throws {\n let gateway = subnet.gateway\n\n var ga = in_addr()\n inet_pton(AF_INET, gateway.description, &ga)\n\n let mask = IPv4Address(fromValue: subnet.prefixLength.prefixMask32)\n var ma = in_addr()\n inet_pton(AF_INET, mask.description, &ma)\n\n guard vmnet_network_configuration_set_ipv4_subnet(config, &ga, &ma) == .VMNET_SUCCESS else {\n throw ContainerizationError(.internalError, message: \"failed to set subnet \\(subnet) for network\")\n }\n }\n }\n\n /// Create a new manager with the provided kernel and initfs mount.\n public init(\n kernel: Kernel,\n initfs: Mount,\n network: Network? = nil\n ) throws {\n self.imageStore = ImageStore.default\n self.network = network\n try Self.createRootDirectory(path: self.imageStore.path)\n self.vmm = VZVirtualMachineManager(\n kernel: kernel,\n initialFilesystem: initfs,\n bootlog: self.imageStore.path.appendingPathComponent(\"bootlog.log\").absolutePath()\n )\n }\n\n /// Create a new manager with the provided kernel and image reference for the initfs.\n public init(\n kernel: Kernel,\n initfsReference: String,\n network: Network? = nil\n ) async throws {\n self.imageStore = ImageStore.default\n self.network = network\n try Self.createRootDirectory(path: self.imageStore.path)\n\n let initPath = self.imageStore.path.appendingPathComponent(\"initfs.ext4\")\n let initImage = try await self.imageStore.getInitImage(reference: initfsReference)\n let initfs = try await {\n do {\n return try await initImage.initBlock(at: initPath, for: .linuxArm)\n } catch let err as ContainerizationError {\n guard err.code == .exists else {\n throw err\n }\n return .block(\n format: \"ext4\",\n source: initPath.absolutePath(),\n destination: \"/\",\n options: [\"ro\"]\n )\n }\n }()\n\n self.vmm = VZVirtualMachineManager(\n kernel: kernel,\n initialFilesystem: initfs,\n bootlog: self.imageStore.path.appendingPathComponent(\"bootlog.log\").absolutePath()\n )\n }\n\n /// Create a new manager with the provided vmm and network.\n public init(\n vmm: any VirtualMachineManager,\n network: Network? = nil\n ) throws {\n self.imageStore = ImageStore.default\n try Self.createRootDirectory(path: self.imageStore.path)\n self.network = network\n self.vmm = vmm\n }\n\n private static func createRootDirectory(path: URL) throws {\n try FileManager.default.createDirectory(\n at: path.appendingPathComponent(\"containers\"),\n withIntermediateDirectories: true\n )\n }\n\n /// Returns a new container from the provided image reference.\n /// - Parameters:\n /// - id: The container ID.\n /// - reference: The image reference.\n /// - rootfsSizeInBytes: The size of the root filesystem in bytes. Defaults to 8 GiB.\n public func create(\n _ id: String,\n reference: String,\n rootfsSizeInBytes: UInt64 = 8.gib(),\n configuration: (inout LinuxContainer.Configuration) throws -> Void\n ) async throws -> LinuxContainer {\n let image = try await imageStore.get(reference: reference, pull: true)\n return try await create(\n id,\n image: image,\n rootfsSizeInBytes: rootfsSizeInBytes,\n configuration: configuration\n )\n }\n\n /// Returns a new container from the provided image.\n /// - Parameters:\n /// - id: The container ID.\n /// - image: The image.\n /// - rootfsSizeInBytes: The size of the root filesystem in bytes. Defaults to 8 GiB.\n public func create(\n _ id: String,\n image: Image,\n rootfsSizeInBytes: UInt64 = 8.gib(),\n configuration: (inout LinuxContainer.Configuration) throws -> Void\n ) async throws -> LinuxContainer {\n let path = try createContainerRoot(id)\n\n let rootfs = try await unpack(\n image: image,\n destination: path.appendingPathComponent(\"rootfs.ext4\"),\n size: rootfsSizeInBytes\n )\n return try await create(\n id,\n image: image,\n rootfs: rootfs,\n configuration: configuration\n )\n }\n\n /// Returns a new container from the provided image and root filesystem mount.\n /// - Parameters:\n /// - id: The container ID.\n /// - image: The image.\n /// - rootfs: The root filesystem mount pointing to an existing block file.\n public func create(\n _ id: String,\n image: Image,\n rootfs: Mount,\n configuration: (inout LinuxContainer.Configuration) throws -> Void\n ) async throws -> LinuxContainer {\n let imageConfig = try await image.config(for: .current).config\n return try LinuxContainer(\n id,\n rootfs: rootfs,\n vmm: self.vmm\n ) { config in\n if let imageConfig {\n config.process = .init(from: imageConfig)\n }\n if let interface = try self.network?.create(id) {\n config.interfaces = [interface]\n config.dns = .init(nameservers: [interface.gateway!])\n }\n try configuration(&config)\n }\n }\n\n /// Returns an existing container from the provided image and root filesystem mount.\n /// - Parameters:\n /// - id: The container ID.\n /// - image: The image.\n public func get(\n _ id: String,\n image: Image,\n ) async throws -> LinuxContainer {\n let path = containerRoot.appendingPathComponent(id)\n guard FileManager.default.fileExists(atPath: path.absolutePath()) else {\n throw ContainerizationError(.notFound, message: \"\\(id) does not exist\")\n }\n\n let rootfs: Mount = .block(\n format: \"ext4\",\n source: path.appendingPathComponent(\"rootfs.ext4\").absolutePath(),\n destination: \"/\",\n options: []\n )\n\n let imageConfig = try await image.config(for: .current).config\n return try LinuxContainer(\n id,\n rootfs: rootfs,\n vmm: self.vmm\n ) { config in\n if let imageConfig {\n config.process = .init(from: imageConfig)\n }\n if let interface = try self.network?.create(id) {\n config.interfaces = [interface]\n config.dns = .init(nameservers: [interface.gateway!])\n }\n }\n }\n\n /// Performs the cleanup of a container.\n /// - Parameter id: The container ID.\n public func delete(_ id: String) throws {\n try self.network?.release(id)\n let path = containerRoot.appendingPathComponent(id)\n try FileManager.default.removeItem(at: path)\n }\n\n private func createContainerRoot(_ id: String) throws -> URL {\n let path = containerRoot.appendingPathComponent(id)\n try FileManager.default.createDirectory(at: path, withIntermediateDirectories: false)\n return path\n }\n\n private func unpack(image: Image, destination: URL, size: UInt64) async throws -> Mount {\n do {\n let unpacker = EXT4Unpacker(blockSizeInBytes: size)\n return try await unpacker.unpack(image, for: .current, at: destination)\n } catch let err as ContainerizationError {\n if err.code == .exists {\n return .block(\n format: \"ext4\",\n source: destination.absolutePath(),\n destination: \"/\",\n options: []\n )\n }\n throw err\n }\n }\n}\n\nextension CIDRAddress {\n /// The gateway address of the network.\n public var gateway: IPv4Address {\n IPv4Address(fromValue: self.lower.value + 1)\n }\n}\n\n@available(macOS 26.0, *)\nprivate struct SendableReference: Sendable {\n nonisolated(unsafe) private let reference: vmnet_network_ref\n}\n\n#endif\n"], ["/containerization/Sources/Containerization/LinuxContainer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport Logging\nimport Synchronization\n\nimport struct ContainerizationOS.Terminal\n\n/// `LinuxContainer` is an easy to use type for launching and managing the\n/// full lifecycle of a Linux container ran inside of a virtual machine.\npublic final class LinuxContainer: Container, Sendable {\n /// The default PATH value for a process.\n public static let defaultPath = \"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\n\n /// The identifier of the container.\n public let id: String\n\n /// Rootfs for the container.\n public let rootfs: Mount\n\n /// Configuration for the container.\n public let config: Configuration\n\n /// The configuration for the LinuxContainer.\n public struct Configuration: Sendable {\n /// Configuration of a container process.\n public struct Process: Sendable {\n /// The arguments for the container process.\n public var arguments: [String] = []\n /// The environment variables for the container process.\n public var environmentVariables: [String] = [\"PATH=\\(LinuxContainer.defaultPath)\"]\n /// The working directory for the container process.\n public var workingDirectory: String = \"/\"\n /// The user the container process will run as.\n public var user: ContainerizationOCI.User = .init()\n /// The rlimits for the container process.\n public var rlimits: [POSIXRlimit] = []\n /// Whether to allocate a pseudo terminal for the process. If you'd like interactive\n /// behavior and are planning to use a terminal for stdin/out/err on the client side,\n /// this should likely be set to true.\n public var terminal: Bool = false\n /// The stdin for the process.\n public var stdin: ReaderStream?\n /// The stdout for the process.\n public var stdout: Writer?\n /// The stderr for the process.\n public var stderr: Writer?\n\n public init() {}\n\n public init(from config: ImageConfig) {\n self.workingDirectory = config.workingDir ?? \"/\"\n self.environmentVariables = config.env ?? []\n self.arguments = (config.entrypoint ?? []) + (config.cmd ?? [])\n self.user = {\n if let rawString = config.user {\n return User(username: rawString)\n }\n return User()\n }()\n }\n\n func toOCI() -> ContainerizationOCI.Process {\n ContainerizationOCI.Process(\n args: self.arguments,\n cwd: self.workingDirectory,\n env: self.environmentVariables,\n user: self.user,\n rlimits: self.rlimits,\n terminal: self.terminal\n )\n }\n\n /// Sets up IO to be handled by the passed in Terminal, and edits the\n /// process configuration to set the necessary state for using a pty.\n mutating public func setTerminalIO(terminal: Terminal) {\n self.environmentVariables.append(\"TERM=xterm\")\n self.terminal = true\n self.stdin = terminal\n self.stdout = terminal\n }\n }\n\n /// Configuration for the init process of the container.\n public var process = Process.init()\n /// The amount of cpus for the container.\n public var cpus: Int = 4\n /// The memory in bytes to give to the container.\n public var memoryInBytes: UInt64 = 1024.mib()\n /// The hostname for the container.\n public var hostname: String = \"\"\n /// The system control options for the container.\n public var sysctl: [String: String] = [:]\n /// The network interfaces for the container.\n public var interfaces: [any Interface] = []\n /// The Unix domain socket relays to setup for the container.\n public var sockets: [UnixSocketConfiguration] = []\n /// Whether rosetta x86-64 emulation should be setup for the container.\n public var rosetta: Bool = false\n /// Whether nested virtualization should be turned on for the container.\n public var virtualization: Bool = false\n /// The mounts for the container.\n public var mounts: [Mount] = LinuxContainer.defaultMounts()\n /// The DNS configuration for the container.\n public var dns: DNS?\n /// The hosts to add to /etc/hosts for the container.\n public var hosts: Hosts?\n\n public init() {}\n }\n\n /// `IOHandler` informs the container process about what should be done\n /// for the stdio streams.\n struct IOHandler: Sendable {\n public var stdin: ReaderStream?\n public var stdout: Writer?\n public var stderr: Writer?\n\n init(stdin: ReaderStream? = nil, stdout: Writer? = nil, stderr: Writer? = nil) {\n self.stdin = stdin\n self.stdout = stdout\n self.stderr = stderr\n }\n }\n\n private let state: Mutex\n\n // Ports to be allocated from for stdio and for\n // unix socket relays that are sharing a guest\n // uds to the host.\n private let hostVsockPorts: Atomic\n // Ports we request the guest to allocate for unix socket relays from\n // the host.\n private let guestVsockPorts: Atomic\n\n private enum State: Sendable {\n /// The container class has been created but no live resources are running.\n case initialized\n /// The container is creating and booting the underlying virtual resources.\n case creating(CreatingState)\n /// The container's virtual machine has been setup and the runtime environment has been configured.\n case created(CreatedState)\n /// The initial process of the container is preparing to start.\n case starting(StartingState)\n /// The initial process of the container has started and is running.\n case started(StartedState)\n /// The container is preparing to stop.\n case stopping(StoppingState)\n /// The container has run and fully stopped.\n case stopped\n /// An error occurred during the lifetime of this class.\n case errored(Swift.Error)\n\n struct CreatingState: Sendable {}\n\n struct CreatedState: Sendable {\n let vm: any VirtualMachineInstance\n let relayManager: UnixSocketRelayManager\n }\n\n struct StartingState: Sendable {\n let vm: any VirtualMachineInstance\n let relayManager: UnixSocketRelayManager\n\n init(_ state: CreatedState) {\n self.vm = state.vm\n self.relayManager = state.relayManager\n }\n }\n\n struct StartedState: Sendable {\n let vm: any VirtualMachineInstance\n let process: LinuxProcess\n let relayManager: UnixSocketRelayManager\n\n init(_ state: StartingState, process: LinuxProcess) {\n self.vm = state.vm\n self.relayManager = state.relayManager\n self.process = process\n }\n }\n\n struct StoppingState: Sendable {\n let vm: any VirtualMachineInstance\n\n init(_ state: StartedState) {\n self.vm = state.vm\n }\n }\n\n mutating func setCreating() throws {\n switch self {\n case .initialized:\n self = .creating(.init())\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in initialized state to start\"\n )\n }\n }\n\n mutating func setCreated(\n vm: any VirtualMachineInstance,\n relayManager: UnixSocketRelayManager\n ) throws {\n switch self {\n case .creating:\n self = .created(.init(vm: vm, relayManager: relayManager))\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in creating state before created\"\n )\n }\n }\n\n mutating func setStarting() throws -> any VirtualMachineInstance {\n switch self {\n case .created(let state):\n self = .starting(.init(state))\n return state.vm\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in created state before starting\"\n )\n }\n }\n\n mutating func setStarted(process: LinuxProcess) throws {\n switch self {\n case .starting(let state):\n self = .started(.init(state, process: process))\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in starting state before started\"\n )\n }\n }\n\n mutating func stopping() throws -> StartedState {\n switch self {\n case .started(let state):\n self = .stopping(.init(state))\n return state\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in a started state before stopping\"\n )\n }\n }\n\n func startedState(_ operation: String) throws -> StartedState {\n switch self {\n case .started(let state):\n return state\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"failed to \\(operation): container must be running\"\n )\n }\n }\n\n mutating func stopped() throws {\n switch self {\n case .stopping(_):\n self = .stopped\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in a stopping state before setting to stopped\"\n )\n }\n }\n\n mutating func errored(error: Swift.Error) {\n self = .errored(error)\n }\n }\n\n private let vmm: VirtualMachineManager\n private let logger: Logger?\n\n /// Create a new `LinuxContainer`. A `Mount` that contains the contents\n /// of the container image must be provided, as well as a `VirtualMachineManager`\n /// instance that will handle launching the virtual machine the container will\n /// execute inside of.\n public init(\n _ id: String,\n rootfs: Mount,\n vmm: VirtualMachineManager,\n logger: Logger? = nil,\n configuration: (inout Configuration) throws -> Void\n ) throws {\n self.id = id\n self.vmm = vmm\n self.hostVsockPorts = Atomic(0x1000_0000)\n self.guestVsockPorts = Atomic(0x1000_0000)\n self.rootfs = rootfs\n self.logger = logger\n\n var config = Configuration()\n try configuration(&config)\n\n self.config = config\n self.state = Mutex(.initialized)\n }\n\n private static func createDefaultRuntimeSpec(_ id: String) -> Spec {\n .init(\n process: .init(),\n hostname: id,\n root: .init(\n path: Self.guestRootfsPath(id),\n readonly: false\n ),\n linux: .init(\n resources: .init()\n )\n )\n }\n\n private func generateRuntimeSpec() -> Spec {\n var spec = Self.createDefaultRuntimeSpec(id)\n\n // Process toggles.\n spec.process = config.process.toOCI()\n\n // General toggles.\n spec.hostname = config.hostname\n\n // Linux toggles.\n var linux = ContainerizationOCI.Linux.init()\n linux.sysctl = config.sysctl\n spec.linux = linux\n\n return spec\n }\n\n public static func defaultMounts() -> [Mount] {\n let defaultOptions = [\"nosuid\", \"noexec\", \"nodev\"]\n return [\n .any(type: \"proc\", source: \"proc\", destination: \"/proc\", options: defaultOptions),\n .any(type: \"sysfs\", source: \"sysfs\", destination: \"/sys\", options: defaultOptions),\n .any(type: \"devtmpfs\", source: \"none\", destination: \"/dev\", options: [\"nosuid\", \"mode=755\"]),\n .any(type: \"mqueue\", source: \"mqueue\", destination: \"/dev/mqueue\", options: defaultOptions),\n .any(type: \"tmpfs\", source: \"tmpfs\", destination: \"/dev/shm\", options: defaultOptions + [\"mode=1777\", \"size=65536k\"]),\n .any(type: \"cgroup2\", source: \"none\", destination: \"/sys/fs/cgroup\", options: defaultOptions),\n .any(type: \"devpts\", source: \"devpts\", destination: \"/dev/pts\", options: [\"nosuid\", \"noexec\", \"gid=5\", \"mode=620\", \"ptmxmode=666\"]),\n ]\n }\n\n private static func guestRootfsPath(_ id: String) -> String {\n \"/run/container/\\(id)/rootfs\"\n }\n}\n\nextension LinuxContainer {\n package var root: String {\n Self.guestRootfsPath(id)\n }\n\n /// Number of CPU cores allocated.\n public var cpus: Int {\n config.cpus\n }\n\n /// Amount of memory in bytes allocated for the container.\n /// This will be aligned to a 1MB boundary if it isn't already.\n public var memoryInBytes: UInt64 {\n config.memoryInBytes\n }\n\n /// Network interfaces of the container.\n public var interfaces: [any Interface] {\n config.interfaces\n }\n\n /// Create the underlying container's virtual machine\n /// and set up the runtime environment.\n public func create() async throws {\n try self.state.withLock { try $0.setCreating() }\n\n let vm = try vmm.create(container: self)\n try await vm.start()\n do {\n try await vm.withAgent { agent in\n let relayManager = UnixSocketRelayManager(vm: vm)\n\n try await agent.standardSetup()\n\n // Mount the rootfs.\n var rootfs = vm.mounts[0].to\n rootfs.destination = Self.guestRootfsPath(self.id)\n try await agent.mount(rootfs)\n\n // Start up our friendly unix socket relays.\n for socket in self.config.sockets {\n try await self.relayUnixSocket(\n socket: socket,\n relayManager: relayManager,\n agent: agent\n )\n }\n\n // For every interface asked for:\n // 1. Add the address requested\n // 2. Online the adapter\n // 3. If a gateway IP address is present, add the default route.\n for (index, i) in self.interfaces.enumerated() {\n let name = \"eth\\(index)\"\n try await agent.addressAdd(name: name, address: i.address)\n try await agent.up(name: name, mtu: 1280)\n if let gateway = i.gateway {\n try await agent.routeAddDefault(name: name, gateway: gateway)\n }\n }\n\n // Setup /etc/resolv.conf and /etc/hosts if asked for.\n if let dns = self.config.dns {\n try await agent.configureDNS(config: dns, location: rootfs.destination)\n }\n if let hosts = self.config.hosts {\n try await agent.configureHosts(config: hosts, location: rootfs.destination)\n }\n\n try self.state.withLock { try $0.setCreated(vm: vm, relayManager: relayManager) }\n }\n } catch {\n try? await vm.stop()\n self.state.withLock { $0.errored(error: error) }\n throw error\n }\n }\n\n /// Start the container container's initial process.\n public func start() async throws {\n let vm = try self.state.withLock { try $0.setStarting() }\n\n let agent = try await vm.dialAgent()\n do {\n var spec = generateRuntimeSpec()\n // We don't need the rootfs, nor do OCI runtimes want it included.\n spec.mounts = vm.mounts.dropFirst().map { $0.to }\n\n let stdio = Self.setupIO(\n portAllocator: self.hostVsockPorts,\n stdin: self.config.process.stdin,\n stdout: self.config.process.stdout,\n stderr: self.config.process.stderr\n )\n\n let process = LinuxProcess(\n self.id,\n containerID: self.id,\n spec: spec,\n io: stdio,\n agent: agent,\n vm: vm,\n logger: self.logger\n )\n try await process.start()\n\n try self.state.withLock { try $0.setStarted(process: process) }\n } catch {\n try? await agent.close()\n self.state.withLock { $0.errored(error: error) }\n throw error\n }\n }\n\n private static func setupIO(\n portAllocator: borrowing Atomic,\n stdin: ReaderStream?,\n stdout: Writer?,\n stderr: Writer?\n ) -> LinuxProcess.Stdio {\n var stdinSetup: LinuxProcess.StdioReaderSetup? = nil\n if let reader = stdin {\n let ret = portAllocator.wrappingAdd(1, ordering: .relaxed)\n stdinSetup = .init(\n port: ret.oldValue,\n reader: reader\n )\n }\n\n var stdoutSetup: LinuxProcess.StdioSetup? = nil\n if let writer = stdout {\n let ret = portAllocator.wrappingAdd(1, ordering: .relaxed)\n stdoutSetup = LinuxProcess.StdioSetup(\n port: ret.oldValue,\n writer: writer\n )\n }\n\n var stderrSetup: LinuxProcess.StdioSetup? = nil\n if let writer = stderr {\n let ret = portAllocator.wrappingAdd(1, ordering: .relaxed)\n stderrSetup = LinuxProcess.StdioSetup(\n port: ret.oldValue,\n writer: writer\n )\n }\n\n return LinuxProcess.Stdio(\n stdin: stdinSetup,\n stdout: stdoutSetup,\n stderr: stderrSetup\n )\n }\n\n /// Stop the container from executing.\n public func stop() async throws {\n let startedState = try self.state.withLock { try $0.stopping() }\n\n try await startedState.relayManager.stopAll()\n\n // It's possible the state of the vm is not in a great spot\n // if the guest panicked or had any sort of bug/fault.\n // First check if the vm is even still running, as trying to\n // use a vsock handle like below here will cause NIO to\n // fatalError because we'll get an EBADF.\n if startedState.vm.state == .stopped {\n try self.state.withLock { try $0.stopped() }\n return\n }\n\n try await startedState.vm.withAgent { agent in\n // First, we need to stop any unix socket relays as this will\n // keep the rootfs from being able to umount (EBUSY).\n let sockets = config.sockets\n if !sockets.isEmpty {\n guard let relayAgent = agent as? SocketRelayAgent else {\n throw ContainerizationError(\n .unsupported,\n message: \"VirtualMachineAgent does not support relaySocket surface\"\n )\n }\n for socket in sockets {\n try await relayAgent.stopSocketRelay(configuration: socket)\n }\n }\n\n // Now lets ensure every process is donezo.\n try await agent.kill(pid: -1, signal: SIGKILL)\n\n // Wait on init proc exit. Give it 5 seconds of leeway.\n _ = try await agent.waitProcess(\n id: self.id,\n containerID: self.id,\n timeoutInSeconds: 5\n )\n\n // Today, we leave EBUSY looping and other fun logic up to the\n // guest agent.\n try await agent.umount(\n path: Self.guestRootfsPath(self.id),\n flags: 0\n )\n }\n\n // Lets free up the init procs resources, as this includes the open agent conn.\n try? await startedState.process.delete()\n\n try await startedState.vm.stop()\n try self.state.withLock { try $0.stopped() }\n }\n\n /// Send a signal to the container.\n public func kill(_ signal: Int32) async throws {\n let state = try self.state.withLock { try $0.startedState(\"kill\") }\n try await state.process.kill(signal)\n }\n\n /// Wait for the container to exit. Returns the exit code.\n @discardableResult\n public func wait(timeoutInSeconds: Int64? = nil) async throws -> Int32 {\n let state = try self.state.withLock { try $0.startedState(\"wait\") }\n return try await state.process.wait(timeoutInSeconds: timeoutInSeconds)\n }\n\n /// Resize the container's terminal (if one was requested). This\n /// will error if terminal was set to false before creating the container.\n public func resize(to: Terminal.Size) async throws {\n let state = try self.state.withLock { try $0.startedState(\"resize\") }\n try await state.process.resize(to: to)\n }\n\n /// Execute a new process in the container.\n public func exec(_ id: String, configuration: (inout Configuration.Process) throws -> Void) async throws -> LinuxProcess {\n let state = try self.state.withLock { try $0.startedState(\"exec\") }\n\n var spec = generateRuntimeSpec()\n var config = Configuration.Process()\n try configuration(&config)\n spec.process = config.toOCI()\n\n let stdio = Self.setupIO(\n portAllocator: self.hostVsockPorts,\n stdin: config.stdin,\n stdout: config.stdout,\n stderr: config.stderr\n )\n let agent = try await state.vm.dialAgent()\n let process = LinuxProcess(\n id,\n containerID: self.id,\n spec: spec,\n io: stdio,\n agent: agent,\n vm: state.vm,\n logger: self.logger\n )\n return process\n }\n\n /// Execute a new process in the container.\n public func exec(_ id: String, configuration: Configuration.Process) async throws -> LinuxProcess {\n let state = try self.state.withLock { try $0.startedState(\"exec\") }\n\n var spec = generateRuntimeSpec()\n spec.process = configuration.toOCI()\n\n let stdio = Self.setupIO(\n portAllocator: self.hostVsockPorts,\n stdin: configuration.stdin,\n stdout: configuration.stdout,\n stderr: configuration.stderr\n )\n let agent = try await state.vm.dialAgent()\n let process = LinuxProcess(\n id,\n containerID: self.id,\n spec: spec,\n io: stdio,\n agent: agent,\n vm: state.vm,\n logger: self.logger\n )\n return process\n }\n\n /// Dial a vsock port in the container.\n public func dialVsock(port: UInt32) async throws -> FileHandle {\n let state = try self.state.withLock { try $0.startedState(\"dialVsock\") }\n return try await state.vm.dial(port)\n }\n\n /// Close the containers standard input to signal no more input is\n /// arriving.\n public func closeStdin() async throws {\n let state = try self.state.withLock { try $0.startedState(\"closeStdin\") }\n return try await state.process.closeStdin()\n }\n\n /// Relay a unix socket from in the container to the host, or from the host\n /// to inside the container.\n public func relayUnixSocket(socket: UnixSocketConfiguration) async throws {\n let state = try self.state.withLock { try $0.startedState(\"relayUnixSocket\") }\n\n try await state.vm.withAgent { agent in\n try await self.relayUnixSocket(\n socket: socket,\n relayManager: state.relayManager,\n agent: agent\n )\n }\n }\n\n private func relayUnixSocket(\n socket: UnixSocketConfiguration,\n relayManager: UnixSocketRelayManager,\n agent: any VirtualMachineAgent\n ) async throws {\n guard let relayAgent = agent as? SocketRelayAgent else {\n throw ContainerizationError(\n .unsupported,\n message: \"VirtualMachineAgent does not support relaySocket surface\"\n )\n }\n\n var socket = socket\n let rootInGuest = URL(filePath: self.root)\n\n if socket.direction == .into {\n socket.destination = rootInGuest.appending(path: socket.destination.path)\n } else {\n socket.source = rootInGuest.appending(path: socket.source.path)\n }\n\n let port = self.hostVsockPorts.wrappingAdd(1, ordering: .relaxed).oldValue\n try await relayManager.start(port: port, socket: socket)\n try await relayAgent.relaySocket(port: port, configuration: socket)\n }\n}\n\nextension VirtualMachineInstance {\n /// Scoped access to an agent instance to ensure the resources are always freed (mostly close(2)'ing\n /// the vsock fd)\n fileprivate func withAgent(fn: @Sendable (VirtualMachineAgent) async throws -> Void) async throws {\n let agent = try await self.dialAgent()\n do {\n try await fn(agent)\n try await agent.close()\n } catch {\n try? await agent.close()\n throw error\n }\n }\n}\n\nextension AttachedFilesystem {\n fileprivate var to: ContainerizationOCI.Mount {\n .init(\n type: self.type,\n source: self.source,\n destination: self.destination,\n options: self.options\n )\n }\n}\n\n#endif\n"], ["/containerization/Sources/cctl/KernelCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport Foundation\n\nextension Application {\n struct KernelCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"kernel\",\n abstract: \"Manage kernel images\",\n subcommands: [\n Create.self\n ]\n )\n\n struct Create: AsyncParsableCommand {\n @Option(name: .shortAndLong, help: \"Name for the kernel image\")\n var name: String\n\n @Option(name: .long, help: \"Labels to add to the built image of the form =, [=,...]\")\n var labels: [String] = []\n\n @Argument var kernels: [String]\n\n func run() async throws {\n let imageStore = Application.imageStore\n let contentStore = Application.contentStore\n let labels = Application.parseKeyValuePairs(from: labels)\n let binaries = try parseBinaries()\n _ = try await KernelImage.create(\n reference: name,\n binaries: binaries,\n labels: labels,\n imageStore: imageStore,\n contentStore: contentStore\n )\n }\n\n func parseBinaries() throws -> [Kernel] {\n var binaries = [Kernel]()\n for rawBinary in kernels {\n let parts = rawBinary.split(separator: \":\")\n guard parts.count == 2 else {\n throw \"Invalid binary format: \\(rawBinary)\"\n }\n let platform: SystemPlatform\n switch parts[1] {\n case \"arm64\":\n platform = .linuxArm\n case \"amd64\":\n platform = .linuxAmd\n default:\n fatalError(\"unsupported platform \\(parts[1])\")\n }\n binaries.append(\n .init(\n path: URL(fileURLWithPath: String(parts[0])),\n platform: platform\n )\n )\n }\n return binaries\n }\n }\n }\n}\n"], ["/containerization/Sources/Integration/ProcessTests.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Crypto\nimport Foundation\nimport Logging\n\nextension IntegrationSuite {\n func testProcessTrue() async throws {\n let id = \"test-process-true\"\n\n let bs = try await bootstrap()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/true\"]\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n }\n\n func testProcessFalse() async throws {\n let id = \"test-process-false\"\n\n let bs = try await bootstrap()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/false\"]\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 1 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 1\")\n }\n }\n\n final class BufferWriter: Writer {\n nonisolated(unsafe) var data = Data()\n\n func write(_ data: Data) throws {\n guard data.count > 0 else {\n return\n }\n self.data.append(data)\n }\n }\n\n final class StdinBuffer: ReaderStream {\n let data: Data\n\n init(data: Data) {\n self.data = data\n }\n\n func stream() -> AsyncStream {\n let (stream, cont) = AsyncStream.makeStream()\n cont.yield(self.data)\n cont.finish()\n return stream\n }\n }\n\n func testProcessEchoHi() async throws {\n let id = \"test-process-echo-hi\"\n let bs = try await bootstrap()\n\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/echo\", \"hi\"]\n config.process.stdout = buffer\n }\n\n do {\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 1\")\n }\n\n guard String(data: buffer.data, encoding: .utf8) == \"hi\\n\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned on stdout 'hi' != '\\(String(data: buffer.data, encoding: .utf8)!)'\")\n }\n } catch {\n try? await container.stop()\n throw error\n }\n }\n\n func testMultipleConcurrentProcesses() async throws {\n let id = \"test-concurrent-processes\"\n\n let bs = try await bootstrap()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/sleep\", \"1000\"]\n }\n\n do {\n try await container.create()\n try await container.start()\n\n try await withThrowingTaskGroup(of: Void.self) { group in\n for i in 0...80 {\n let exec = try await container.exec(\"exec-\\(i)\") { config in\n config.arguments = [\"/bin/true\"]\n }\n\n group.addTask {\n try await exec.start()\n let status = try await exec.wait()\n if status != 0 {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n try await exec.delete()\n }\n }\n\n // wait for all the exec'd processes.\n try await group.waitForAll()\n print(\"all group processes exit\")\n\n // kill the init process.\n try await container.kill(SIGKILL)\n let status = try await container.wait()\n try await container.stop()\n print(\"\\(status)\")\n }\n } catch {\n throw error\n }\n }\n\n func testMultipleConcurrentProcessesOutputStress() async throws {\n let id = \"test-concurrent-processes-output-stress\"\n let bs = try await bootstrap()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/sleep\", \"1000\"]\n }\n\n do {\n try await container.create()\n try await container.start()\n\n let buffer = BufferWriter()\n let exec = try await container.exec(\"expected-value\") { config in\n config.arguments = [\n \"sh\",\n \"-c\",\n \"dd if=/dev/random of=/tmp/bytes bs=1M count=20 status=none ; sha256sum /tmp/bytes\",\n ]\n config.stdout = buffer\n }\n\n try await exec.start()\n let status = try await exec.wait()\n if status != 0 {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n let output = String(data: buffer.data, encoding: .utf8)!\n let expected = String(output.split(separator: \" \").first!)\n try await withThrowingTaskGroup(of: Void.self) { group in\n for i in 0...80 {\n let idx = i\n group.addTask {\n let buffer = BufferWriter()\n let exec = try await container.exec(\"exec-\\(idx)\") { config in\n config.arguments = [\"cat\", \"/tmp/bytes\"]\n config.stdout = buffer\n }\n try await exec.start()\n\n let status = try await exec.wait()\n if status != 0 {\n throw IntegrationError.assert(msg: \"process \\(idx) status \\(status) != 0\")\n }\n\n var hasher = SHA256()\n hasher.update(data: buffer.data)\n let hash = hasher.finalize().digestString.trimmingDigestPrefix\n guard hash == expected else {\n throw IntegrationError.assert(\n msg: \"process \\(idx) output \\(hash) != expected \\(expected)\")\n }\n try await exec.delete()\n }\n }\n\n // wait for all the exec'd processes.\n try await group.waitForAll()\n print(\"all group processes exit\")\n\n // kill the init process.\n try await container.kill(SIGKILL)\n try await container.wait()\n try await container.stop()\n }\n }\n }\n\n func testProcessUser() async throws {\n let id = \"test-process-user\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/usr/bin/id\"]\n config.process.user = .init(uid: 1, gid: 1, additionalGids: [1])\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n let expected = \"uid=1(bin) gid=1(bin) groups=1(bin)\"\n\n guard String(data: buffer.data, encoding: .utf8) == \"\\(expected)\\n\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned on stdout '\\(expected)' != '\\(String(data: buffer.data, encoding: .utf8)!)'\")\n }\n }\n\n // Ensure if we ask for a terminal we set TERM.\n func testProcessTtyEnvvar() async throws {\n let id = \"test-process-tty-envvar\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"env\"]\n config.process.terminal = true\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n guard let str = String(data: buffer.data, encoding: .utf8) else {\n throw IntegrationError.assert(\n msg: \"failed to convert standard output to a UTF8 string\")\n }\n\n let homeEnvvar = \"TERM=xterm\"\n guard str.contains(homeEnvvar) else {\n throw IntegrationError.assert(\n msg: \"process should have TERM environment variable defined\")\n }\n }\n\n // Make sure we set HOME by default if we can find it in /etc/passwd in the guest.\n func testProcessHomeEnvvar() async throws {\n let id = \"test-process-home-envvar\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"env\"]\n config.process.user = .init(uid: 0, gid: 0)\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n guard let str = String(data: buffer.data, encoding: .utf8) else {\n throw IntegrationError.assert(\n msg: \"failed to convert standard output to a UTF8 string\")\n }\n\n let homeEnvvar = \"HOME=/root\"\n guard str.contains(homeEnvvar) else {\n throw IntegrationError.assert(\n msg: \"process should have HOME environment variable defined\")\n }\n }\n\n func testProcessCustomHomeEnvvar() async throws {\n let id = \"test-process-custom-home-envvar\"\n\n let bs = try await bootstrap()\n let customHomeEnvvar = \"HOME=/tmp/custom/home\"\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"sh\", \"-c\", \"echo HOME=$HOME\"]\n config.process.environmentVariables.append(customHomeEnvvar)\n config.process.user = .init(uid: 0, gid: 0)\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n guard let output = String(data: buffer.data, encoding: .utf8) else {\n throw IntegrationError.assert(msg: \"failed to convert stdout to UTF8\")\n }\n\n guard output.contains(customHomeEnvvar) else {\n throw IntegrationError.assert(msg: \"process should have preserved custom HOME environment variable, expected \\(customHomeEnvvar), got: \\(output)\")\n }\n }\n\n func testHostname() async throws {\n let id = \"test-container-hostname\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/hostname\"]\n config.hostname = \"foo-bar\"\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n let expected = \"foo-bar\"\n\n guard String(data: buffer.data, encoding: .utf8) == \"\\(expected)\\n\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned on stdout '\\(expected)' != '\\(String(data: buffer.data, encoding: .utf8)!)'\")\n }\n }\n\n func testHostsFile() async throws {\n let id = \"test-container-hosts-file\"\n\n let bs = try await bootstrap()\n let entry = Hosts.Entry.localHostIPV4(comment: \"Testaroo\")\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"cat\", \"/etc/hosts\"]\n config.hosts = Hosts(entries: [entry])\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n let expected = entry.rendered\n guard String(data: buffer.data, encoding: .utf8) == \"\\(expected)\\n\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned on stdout '\\(expected)' != '\\(String(data: buffer.data, encoding: .utf8)!)'\")\n }\n }\n\n func testProcessStdin() async throws {\n let id = \"test-container-stdin\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"cat\"]\n config.process.stdin = StdinBuffer(data: \"Hello from test\".data(using: .utf8)!)\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n let expected = \"Hello from test\"\n\n guard String(data: buffer.data, encoding: .utf8) == \"\\(expected)\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned on stdout '\\(expected)' != '\\(String(data: buffer.data, encoding: .utf8)!)'\")\n }\n }\n}\n"], ["/containerization/Sources/cctl/RootfsCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationEXT4\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\n\nextension Application {\n struct Rootfs: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"rootfs\",\n abstract: \"Manage the root filesystem for a container\",\n subcommands: [\n Create.self\n ]\n )\n\n struct Create: AsyncParsableCommand {\n @Option(name: .long, help: \"Path to vminitd\")\n var vminitd: String\n\n @Option(name: .long, help: \"Path to vmexec\")\n var vmexec: String\n\n @Option(name: .long, help: \"Platform of the built binaries being packaged into the block\")\n var platformString: String = Platform.current.description\n\n @Option(name: .long, help: \"Labels to add to the built image of the form =, [=,...]\")\n var labels: [String] = []\n\n @Argument var rootfsPath: String\n\n @Argument var tag: String\n\n private static let directories = [\n \"bin\",\n \"sbin\",\n \"dev\",\n \"sys\",\n \"proc/self\", // hack for swift init's booting\n \"run\",\n \"tmp\",\n \"mnt\",\n \"var\",\n ]\n\n func run() async throws {\n try await writeArchive()\n let p = try Platform(from: platformString)\n let rootfs = URL(filePath: rootfsPath)\n let labels = Application.parseKeyValuePairs(from: labels)\n _ = try await InitImage.create(\n reference: tag, rootfs: rootfs,\n platform: p, labels: labels,\n imageStore: Application.imageStore,\n contentStore: Application.contentStore)\n }\n\n private func writeArchive() async throws {\n let writer = try ArchiveWriter(format: .pax, filter: .gzip, file: URL(filePath: rootfsPath))\n let ts = Date()\n let entry = WriteEntry()\n entry.permissions = 0o755\n entry.modificationDate = ts\n entry.creationDate = ts\n entry.group = 0\n entry.owner = 0\n entry.fileType = .directory\n // create the initial directory structure.\n for dir in Self.directories {\n entry.path = dir\n try writer.writeEntry(entry: entry, data: nil)\n }\n\n entry.fileType = .regular\n entry.path = \"sbin/vminitd\"\n\n var src = URL(fileURLWithPath: vminitd)\n var data = try Data(contentsOf: src)\n entry.size = Int64(data.count)\n try writer.writeEntry(entry: entry, data: data)\n\n src = URL(fileURLWithPath: vmexec)\n data = try Data(contentsOf: src)\n entry.path = \"sbin/vmexec\"\n entry.size = Int64(data.count)\n try writer.writeEntry(entry: entry, data: data)\n\n entry.fileType = .symbolicLink\n entry.path = \"proc/self/exe\"\n entry.symlinkTarget = \"sbin/vminitd\"\n entry.size = nil\n try writer.writeEntry(entry: entry, data: data)\n try writer.finishEncoding()\n }\n }\n }\n}\n"], ["/containerization/Sources/Containerization/VZVirtualMachineInstance.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Logging\nimport NIOCore\nimport NIOPosix\nimport Synchronization\nimport Virtualization\n\nstruct VZVirtualMachineInstance: VirtualMachineInstance, Sendable {\n typealias Agent = Vminitd\n\n /// Attached mounts on the sandbox.\n public let mounts: [AttachedFilesystem]\n\n /// Returns the runtime state of the vm.\n public var state: VirtualMachineInstanceState {\n vzStateToInstanceState()\n }\n\n /// The sandbox configuration.\n private let config: Configuration\n public struct Configuration: Sendable {\n /// Amount of cpus to allocated.\n public var cpus: Int\n /// Amount of memory in bytes allocated.\n public var memoryInBytes: UInt64\n /// Toggle rosetta's x86_64 emulation support.\n public var rosetta: Bool\n /// Toggle nested virtualization support.\n public var nestedVirtualization: Bool\n /// Mount attachments.\n public var mounts: [Mount]\n /// Network interface attachments.\n public var interfaces: [any Interface]\n /// Kernel image.\n public var kernel: Kernel?\n /// The root filesystem.\n public var initialFilesystem: Mount?\n /// File path to store the sandbox boot logs.\n public var bootlog: URL?\n\n init() {\n self.cpus = 4\n self.memoryInBytes = 1024.mib()\n self.rosetta = false\n self.nestedVirtualization = false\n self.mounts = []\n self.interfaces = []\n }\n }\n\n private nonisolated(unsafe) let vm: VZVirtualMachine\n private let queue: DispatchQueue\n private let group: MultiThreadedEventLoopGroup\n private let lock: AsyncLock\n private let timeSyncer: TimeSyncer\n private let logger: Logger?\n\n public init(\n group: MultiThreadedEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount),\n logger: Logger? = nil,\n with: (inout Configuration) throws -> Void\n ) throws {\n var config = Configuration()\n try with(&config)\n try self.init(group: group, config: config, logger: logger)\n }\n\n init(group: MultiThreadedEventLoopGroup, config: Configuration, logger: Logger?) throws {\n self.config = config\n self.group = group\n self.lock = .init()\n self.queue = DispatchQueue(label: \"com.apple.containerization.sandbox.\\(UUID().uuidString)\")\n self.mounts = try config.mountAttachments()\n self.logger = logger\n self.timeSyncer = .init(logger: logger)\n\n self.vm = VZVirtualMachine(\n configuration: try config.toVZ(),\n queue: self.queue\n )\n }\n}\n\nextension VZVirtualMachineInstance {\n func vzStateToInstanceState() -> VirtualMachineInstanceState {\n self.queue.sync {\n let state: VirtualMachineInstanceState\n switch self.vm.state {\n case .starting:\n state = .starting\n case .running:\n state = .running\n case .stopping:\n state = .stopping\n case .stopped:\n state = .stopped\n default:\n state = .unknown\n }\n return state\n }\n }\n\n func start() async throws {\n try await lock.withLock { _ in\n guard self.state == .stopped else {\n throw ContainerizationError(\n .invalidState,\n message: \"sandbox is not stopped \\(self.state)\"\n )\n }\n\n // Do any necessary setup needed prior to starting the guest.\n try await self.prestart()\n\n try await self.vm.start(queue: self.queue)\n\n let agent = Vminitd(\n connection: try await self.vm.waitForAgent(queue: self.queue),\n group: self.group\n )\n\n do {\n if self.config.rosetta {\n try await agent.enableRosetta()\n }\n } catch {\n try await agent.close()\n throw error\n }\n\n // Don't close our remote context as we are providing\n // it to our time sync routine.\n await self.timeSyncer.start(context: agent)\n }\n }\n\n func stop() async throws {\n try await lock.withLock { _ in\n // NOTE: We should record HOW the vm stopped eventually. If the vm exited\n // unexpectedly virtualization framework offers you a way to store\n // an error on how it exited. We should report that here instead of the\n // generic vm is not running.\n guard self.state == .running else {\n throw ContainerizationError(.invalidState, message: \"vm is not running\")\n }\n\n try await self.timeSyncer.close()\n\n try await self.vm.stop(queue: self.queue)\n try await self.group.shutdownGracefully()\n }\n }\n\n public func dialAgent() async throws -> Vminitd {\n let conn = try await dial(Vminitd.port)\n return Vminitd(connection: conn, group: self.group)\n }\n}\n\nextension VZVirtualMachineInstance {\n func dial(_ port: UInt32) async throws -> FileHandle {\n try await vm.connect(\n queue: queue,\n port: port\n ).dupHandle()\n }\n\n func listen(_ port: UInt32) throws -> VsockConnectionStream {\n let stream = VsockConnectionStream(port: port)\n let listener = VZVirtioSocketListener()\n listener.delegate = stream\n\n try self.vm.listen(\n queue: queue,\n port: port,\n listener: listener\n )\n return stream\n }\n\n func stopListen(_ port: UInt32) throws {\n try self.vm.removeListener(\n queue: queue,\n port: port\n )\n }\n\n func prestart() async throws {\n if self.config.rosetta {\n #if arch(arm64)\n if VZLinuxRosettaDirectoryShare.availability == .notInstalled {\n self.logger?.info(\"installing rosetta\")\n try await VZVirtualMachineInstance.Configuration.installRosetta()\n }\n #else\n fatalError(\"rosetta is only supported on arm64\")\n #endif\n }\n }\n}\n\nextension VZVirtualMachineInstance.Configuration {\n public static func installRosetta() async throws {\n do {\n #if arch(arm64)\n try await VZLinuxRosettaDirectoryShare.installRosetta()\n #else\n fatalError(\"rosetta is only supported on arm64\")\n #endif\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to install rosetta\",\n cause: error\n )\n }\n }\n\n private func serialPort(path: URL) throws -> [VZVirtioConsoleDeviceSerialPortConfiguration] {\n let c = VZVirtioConsoleDeviceSerialPortConfiguration()\n c.attachment = try VZFileSerialPortAttachment(url: path, append: true)\n return [c]\n }\n\n func toVZ() throws -> VZVirtualMachineConfiguration {\n var config = VZVirtualMachineConfiguration()\n\n config.cpuCount = self.cpus\n config.memorySize = self.memoryInBytes\n config.entropyDevices = [VZVirtioEntropyDeviceConfiguration()]\n config.socketDevices = [VZVirtioSocketDeviceConfiguration()]\n if let bootlog = self.bootlog {\n config.serialPorts = try serialPort(path: bootlog)\n }\n\n config.networkDevices = try self.interfaces.map {\n guard let vzi = $0 as? VZInterface else {\n throw ContainerizationError(.invalidArgument, message: \"interface type not supported by VZ\")\n }\n return try vzi.device()\n }\n\n if self.rosetta {\n #if arch(arm64)\n switch VZLinuxRosettaDirectoryShare.availability {\n case .notSupported:\n throw ContainerizationError(\n .invalidArgument,\n message: \"rosetta was requested but is not supported on this machine\"\n )\n case .notInstalled:\n // NOTE: If rosetta isn't installed, we'll error with a nice error message\n // during .start() of the virtual machine instance.\n fallthrough\n case .installed:\n let share = try VZLinuxRosettaDirectoryShare()\n let device = VZVirtioFileSystemDeviceConfiguration(tag: \"rosetta\")\n device.share = share\n config.directorySharingDevices.append(device)\n @unknown default:\n throw ContainerizationError(\n .invalidArgument,\n message: \"unknown rosetta availability encountered: \\(VZLinuxRosettaDirectoryShare.availability)\"\n )\n }\n #else\n fatalError(\"rosetta is only supported on arm64\")\n #endif\n }\n\n guard let kernel = self.kernel else {\n throw ContainerizationError(.invalidArgument, message: \"kernel cannot be nil\")\n }\n\n guard let initialFilesystem = self.initialFilesystem else {\n throw ContainerizationError(.invalidArgument, message: \"rootfs cannot be nil\")\n }\n\n let loader = VZLinuxBootLoader(kernelURL: kernel.path)\n loader.commandLine = kernel.linuxCommandline(initialFilesystem: initialFilesystem)\n config.bootLoader = loader\n\n try initialFilesystem.configure(config: &config)\n for mount in self.mounts {\n try mount.configure(config: &config)\n }\n\n let platform = VZGenericPlatformConfiguration()\n // We shouldn't silently succeed if the user asked for virt and their hardware does\n // not support it.\n if !VZGenericPlatformConfiguration.isNestedVirtualizationSupported && self.nestedVirtualization {\n throw ContainerizationError(\n .unsupported,\n message: \"nested virtualization is not supported on the platform\"\n )\n }\n platform.isNestedVirtualizationEnabled = self.nestedVirtualization\n config.platform = platform\n\n try config.validate()\n return config\n }\n\n func mountAttachments() throws -> [AttachedFilesystem] {\n let allocator = Character.blockDeviceTagAllocator()\n if let initialFilesystem {\n // When the initial filesystem is a blk, allocate the first letter \"vd(a)\"\n // as that is what this blk will be attached under.\n if initialFilesystem.isBlock {\n _ = try allocator.allocate()\n }\n }\n\n var attachments: [AttachedFilesystem] = []\n for mount in self.mounts {\n attachments.append(try .init(mount: mount, allocator: allocator))\n }\n return attachments\n }\n}\n\nextension Mount {\n var isBlock: Bool {\n type == \"ext4\"\n }\n}\n\nextension Kernel {\n func linuxCommandline(initialFilesystem: Mount) -> String {\n var args = self.commandLine.kernelArgs\n\n args.append(\"init=/sbin/vminitd\")\n // rootfs is always set as ro.\n args.append(\"ro\")\n\n switch initialFilesystem.type {\n case \"virtiofs\":\n args.append(contentsOf: [\n \"rootfstype=virtiofs\",\n \"root=rootfs\",\n ])\n case \"ext4\":\n args.append(contentsOf: [\n \"rootfstype=ext4\",\n \"root=/dev/vda\",\n ])\n default:\n fatalError(\"unsupported initfs filesystem \\(initialFilesystem.type)\")\n }\n\n if self.commandLine.initArgs.count > 0 {\n args.append(\"--\")\n args.append(contentsOf: self.commandLine.initArgs)\n }\n\n return args.joined(separator: \" \")\n }\n}\n\npublic protocol VZInterface {\n func device() throws -> VZVirtioNetworkDeviceConfiguration\n}\n\nextension NATInterface: VZInterface {\n public func device() throws -> VZVirtioNetworkDeviceConfiguration {\n let config = VZVirtioNetworkDeviceConfiguration()\n if let macAddress = self.macAddress {\n guard let mac = VZMACAddress(string: macAddress) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid mac address \\(macAddress)\")\n }\n config.macAddress = mac\n }\n config.attachment = VZNATNetworkDeviceAttachment()\n return config\n }\n}\n\n#endif\n"], ["/containerization/Sources/Containerization/Agent/Vminitd.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport GRPC\nimport NIOPosix\n\n/// A remote connection into the vminitd Linux guest agent via a port (vsock).\n/// Used to modify the runtime environment of the Linux sandbox.\npublic struct Vminitd: Sendable {\n public typealias Client = Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClient\n\n // Default vsock port that the agent and client use.\n public static let port: UInt32 = 1024\n\n private static let defaultPath = \"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\n\n let client: Client\n\n public init(client: Client) {\n self.client = client\n }\n\n public init(connection: FileHandle, group: MultiThreadedEventLoopGroup) {\n self.client = .init(connection: connection, group: group)\n }\n\n /// Close the connection to the guest agent.\n public func close() async throws {\n try await client.close()\n }\n}\n\nextension Vminitd: VirtualMachineAgent {\n /// Perform the standard guest setup necessary for vminitd to be able to\n /// run containers.\n public func standardSetup() async throws {\n try await up(name: \"lo\")\n\n try await setenv(key: \"PATH\", value: Self.defaultPath)\n\n let mounts: [ContainerizationOCI.Mount] = [\n // NOTE: /proc is always done implicitly by the guest agent.\n .init(type: \"tmpfs\", source: \"tmpfs\", destination: \"/run\"),\n .init(type: \"sysfs\", source: \"sysfs\", destination: \"/sys\"),\n .init(type: \"tmpfs\", source: \"tmpfs\", destination: \"/tmp\"),\n .init(type: \"devpts\", source: \"devpts\", destination: \"/dev/pts\", options: [\"gid=5\", \"mode=620\", \"ptmxmode=666\"]),\n .init(type: \"cgroup2\", source: \"none\", destination: \"/sys/fs/cgroup\"),\n ]\n for mount in mounts {\n try await self.mount(mount)\n }\n }\n\n /// Mount a filesystem in the sandbox's environment.\n public func mount(_ mount: ContainerizationOCI.Mount) async throws {\n _ = try await client.mount(\n .with {\n $0.type = mount.type\n $0.source = mount.source\n $0.destination = mount.destination\n $0.options = mount.options\n })\n }\n\n /// Unmount a filesystem in the sandbox's environment.\n public func umount(path: String, flags: Int32) async throws {\n _ = try await client.umount(\n .with {\n $0.path = path\n $0.flags = flags\n })\n }\n\n /// Create a directory inside the sandbox's environment.\n public func mkdir(path: String, all: Bool, perms: UInt32) async throws {\n _ = try await client.mkdir(\n .with {\n $0.path = path\n $0.all = all\n $0.perms = perms\n })\n }\n\n public func createProcess(\n id: String,\n containerID: String?,\n stdinPort: UInt32?,\n stdoutPort: UInt32?,\n stderrPort: UInt32?,\n configuration: ContainerizationOCI.Spec,\n options: Data?\n ) async throws {\n let enc = JSONEncoder()\n _ = try await client.createProcess(\n .with {\n $0.id = id\n if let stdinPort {\n $0.stdin = stdinPort\n }\n if let stdoutPort {\n $0.stdout = stdoutPort\n }\n if let stderrPort {\n $0.stderr = stderrPort\n }\n if let containerID {\n $0.containerID = containerID\n }\n $0.configuration = try enc.encode(configuration)\n })\n }\n\n @discardableResult\n public func startProcess(id: String, containerID: String?) async throws -> Int32 {\n let request = Com_Apple_Containerization_Sandbox_V3_StartProcessRequest.with {\n $0.id = id\n if let containerID {\n $0.containerID = containerID\n }\n }\n let resp = try await client.startProcess(request)\n return resp.pid\n }\n\n public func signalProcess(id: String, containerID: String?, signal: Int32) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_KillProcessRequest.with {\n $0.id = id\n $0.signal = signal\n if let containerID {\n $0.containerID = containerID\n }\n }\n _ = try await client.killProcess(request)\n }\n\n public func resizeProcess(id: String, containerID: String?, columns: UInt32, rows: UInt32) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest.with {\n if let containerID {\n $0.containerID = containerID\n }\n $0.id = id\n $0.columns = columns\n $0.rows = rows\n }\n _ = try await client.resizeProcess(request)\n }\n\n public func waitProcess(id: String, containerID: String?, timeoutInSeconds: Int64? = nil) async throws -> Int32 {\n let request = Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest.with {\n $0.id = id\n if let containerID {\n $0.containerID = containerID\n }\n }\n var callOpts: CallOptions?\n if let timeoutInSeconds {\n var copts = CallOptions()\n copts.timeLimit = .timeout(.seconds(timeoutInSeconds))\n callOpts = copts\n }\n do {\n let resp = try await client.waitProcess(request, callOptions: callOpts)\n return resp.exitCode\n } catch {\n if let err = error as? GRPCError.RPCTimedOut {\n throw ContainerizationError(\n .timeout,\n message: \"failed to wait for process exit within timeout of \\(timeoutInSeconds!) seconds\",\n cause: err\n )\n }\n throw error\n }\n }\n\n public func deleteProcess(id: String, containerID: String?) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest.with {\n $0.id = id\n if let containerID {\n $0.containerID = containerID\n }\n }\n _ = try await client.deleteProcess(request)\n }\n\n public func closeProcessStdin(id: String, containerID: String?) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest.with {\n $0.id = id\n if let containerID {\n $0.containerID = containerID\n }\n }\n _ = try await client.closeProcessStdin(request)\n }\n\n public func up(name: String, mtu: UInt32? = nil) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest.with {\n $0.interface = name\n $0.up = true\n if let mtu { $0.mtu = mtu }\n }\n _ = try await client.ipLinkSet(request)\n }\n\n public func down(name: String) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest.with {\n $0.interface = name\n $0.up = false\n }\n _ = try await client.ipLinkSet(request)\n }\n\n /// Get an environment variable from the sandbox's environment.\n public func getenv(key: String) async throws -> String {\n let response = try await client.getenv(\n .with {\n $0.key = key\n })\n return response.value\n }\n\n /// Set an environment variable in the sandbox's environment.\n public func setenv(key: String, value: String) async throws {\n _ = try await client.setenv(\n .with {\n $0.key = key\n $0.value = value\n })\n }\n}\n\n/// Vminitd specific rpcs.\nextension Vminitd {\n /// Sets up an emulator in the guest.\n public func setupEmulator(binaryPath: String, configuration: Binfmt.Entry) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest.with {\n $0.binaryPath = binaryPath\n $0.name = configuration.name\n $0.type = configuration.type\n $0.offset = configuration.offset\n $0.magic = configuration.magic\n $0.mask = configuration.mask\n $0.flags = configuration.flags\n }\n _ = try await client.setupEmulator(request)\n }\n\n /// Sets the guest time.\n public func setTime(sec: Int64, usec: Int32) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_SetTimeRequest.with {\n $0.sec = sec\n $0.usec = usec\n }\n _ = try await client.setTime(request)\n }\n\n /// Set the provided sysctls inside the Sandbox's environment.\n public func sysctl(settings: [String: String]) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_SysctlRequest.with {\n $0.settings = settings\n }\n _ = try await client.sysctl(request)\n }\n\n /// Add an IP address to the sandbox's network interfaces.\n public func addressAdd(name: String, address: String) async throws {\n _ = try await client.ipAddrAdd(\n .with {\n $0.interface = name\n $0.address = address\n })\n }\n\n /// Set the default route in the sandbox's environment.\n public func routeAddDefault(name: String, gateway: String) async throws {\n _ = try await client.ipRouteAddDefault(\n .with {\n $0.interface = name\n $0.gateway = gateway\n })\n }\n\n /// Configure DNS within the sandbox's environment.\n public func configureDNS(config: DNS, location: String) async throws {\n _ = try await client.configureDns(\n .with {\n $0.location = location\n $0.nameservers = config.nameservers\n if let domain = config.domain {\n $0.domain = domain\n }\n $0.searchDomains = config.searchDomains\n $0.options = config.options\n })\n }\n\n /// Configure /etc/hosts within the sandbox's environment.\n public func configureHosts(config: Hosts, location: String) async throws {\n _ = try await client.configureHosts(config.toAgentHostsRequest(location: location))\n }\n\n /// Perform a sync call.\n public func sync() async throws {\n _ = try await client.sync(.init())\n }\n\n public func kill(pid: Int32, signal: Int32) async throws -> Int32 {\n let response = try await client.kill(\n .with {\n $0.pid = pid\n $0.signal = signal\n })\n return response.result\n }\n\n /// Syncing shutdown will send a SIGTERM to all processes\n /// and wait, perform a sync operation, then issue a SIGKILL\n /// to the remaining processes before syncing again.\n public func syncingShutdown() async throws {\n _ = try await self.kill(pid: -1, signal: SIGTERM)\n try await Task.sleep(for: .milliseconds(10))\n try await self.sync()\n\n _ = try await self.kill(pid: -1, signal: SIGKILL)\n try await Task.sleep(for: .milliseconds(10))\n try await self.sync()\n }\n}\n\nextension Hosts {\n func toAgentHostsRequest(location: String) -> Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest {\n Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.with {\n $0.location = location\n if let comment {\n $0.comment = comment\n }\n $0.entries = entries.map {\n let entry = $0\n return Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.HostsEntry.with {\n if let comment = entry.comment {\n $0.comment = comment\n }\n $0.ipAddress = entry.ipAddress\n $0.hostnames = entry.hostnames\n }\n }\n }\n }\n}\n\nextension Vminitd.Client {\n public init(socket: String, group: MultiThreadedEventLoopGroup) {\n var config = ClientConnection.Configuration.default(\n target: .unixDomainSocket(socket),\n eventLoopGroup: group\n )\n config.maximumReceiveMessageLength = Int(64.mib())\n config.connectionBackoff = ConnectionBackoff(retries: .upTo(5))\n\n self = .init(channel: ClientConnection(configuration: config))\n }\n\n public init(connection: FileHandle, group: MultiThreadedEventLoopGroup) {\n var config = ClientConnection.Configuration.default(\n target: .connectedSocket(connection.fileDescriptor),\n eventLoopGroup: group\n )\n config.maximumReceiveMessageLength = Int(64.mib())\n config.connectionBackoff = ConnectionBackoff(retries: .upTo(5))\n\n self = .init(channel: ClientConnection(configuration: config))\n }\n\n public func close() async throws {\n try await self.channel.close().get()\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/Server+GRPC.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport ContainerizationNetlink\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport GRPC\nimport Logging\nimport NIOCore\nimport NIOPosix\nimport _NIOFileSystem\n\nprivate let _setenv = Foundation.setenv\n\n#if canImport(Musl)\nimport Musl\nprivate let _mount = Musl.mount\nprivate let _umount = Musl.umount2\nprivate let _kill = Musl.kill\nprivate let _sync = Musl.sync\n#elseif canImport(Glibc)\nimport Glibc\nprivate let _mount = Glibc.mount\nprivate let _umount = Glibc.umount2\nprivate let _kill = Glibc.kill\nprivate let _sync = Glibc.sync\n#endif\n\nextension Initd: Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncProvider {\n func setTime(\n request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetTimeResponse {\n log.debug(\n \"setTime\",\n metadata: [\n \"sec\": \"\\(request.sec)\",\n \"usec\": \"\\(request.usec)\",\n ])\n\n var tv = timeval(tv_sec: time_t(request.sec), tv_usec: suseconds_t(request.usec))\n guard settimeofday(&tv, nil) == 0 else {\n let error = swiftErrno(\"settimeofday\")\n log.error(\n \"setTime\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"failed to settimeofday: \\(error)\")\n }\n\n return .init()\n }\n\n func setupEmulator(\n request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse {\n log.debug(\n \"setupEmulator\",\n metadata: [\n \"request\": \"\\(request)\"\n ])\n\n if !Binfmt.mounted() {\n throw GRPCStatus(\n code: .internalError,\n message: \"\\(Binfmt.path) is not mounted\"\n )\n }\n\n do {\n let bfmt = Binfmt.Entry(\n name: request.name,\n type: request.type,\n offset: request.offset,\n magic: request.magic,\n mask: request.mask,\n flags: request.flags\n )\n try bfmt.register(binaryPath: request.binaryPath)\n } catch {\n log.error(\n \"setupEmulator\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"setupEmulator: failed to register binfmt_misc entry: \\(error)\"\n )\n }\n\n return .init()\n }\n\n func sysctl(\n request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SysctlResponse {\n log.debug(\n \"sysctl\",\n metadata: [\n \"settings\": \"\\(request.settings)\"\n ])\n\n do {\n let sysctlPath = URL(fileURLWithPath: \"/proc/sys/\")\n for (k, v) in request.settings {\n guard let data = v.data(using: .ascii) else {\n throw GRPCStatus(code: .internalError, message: \"failed to convert \\(v) to data buffer for sysctl write\")\n }\n\n let setting =\n sysctlPath\n .appendingPathComponent(k.replacingOccurrences(of: \".\", with: \"/\"))\n let fh = try FileHandle(forWritingTo: setting)\n defer { try? fh.close() }\n\n try fh.write(contentsOf: data)\n }\n } catch {\n log.error(\n \"sysctl\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"sysctl: failed to set sysctl: \\(error)\"\n )\n }\n\n return .init()\n }\n\n func proxyVsock(\n request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse {\n log.debug(\n \"proxyVsock\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"port\": \"\\(request.vsockPort)\",\n \"guestPath\": \"\\(request.guestPath)\",\n \"action\": \"\\(request.action)\",\n ])\n\n do {\n let proxy = VsockProxy(\n id: request.id,\n action: request.action == .into ? .dial : .listen,\n port: request.vsockPort,\n path: URL(fileURLWithPath: request.guestPath),\n udsPerms: request.guestSocketPermissions,\n log: log\n )\n\n try proxy.start()\n try await state.add(proxy: proxy)\n } catch {\n log.error(\n \"proxyVsock\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"proxyVsock: failed to setup vsock proxy: \\(error)\"\n )\n }\n\n return .init()\n }\n\n func stopVsockProxy(\n request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse {\n log.debug(\n \"stopVsockProxy\",\n metadata: [\n \"id\": \"\\(request.id)\"\n ])\n\n do {\n let proxy = try await state.remove(proxy: request.id)\n try proxy.close()\n } catch {\n log.error(\n \"stopVsockProxy\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"stopVsockProxy: failed to stop vsock proxy: \\(error)\"\n )\n }\n\n return .init()\n }\n\n func mkdir(request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest, context: GRPC.GRPCAsyncServerCallContext)\n async throws -> Com_Apple_Containerization_Sandbox_V3_MkdirResponse\n {\n log.debug(\n \"mkdir\",\n metadata: [\n \"path\": \"\\(request.path)\",\n \"all\": \"\\(request.all)\",\n ])\n\n do {\n try FileManager.default.createDirectory(\n atPath: request.path,\n withIntermediateDirectories: request.all\n )\n } catch {\n log.error(\n \"mkdir\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"mkdir: \\(error)\")\n }\n\n return .init()\n }\n\n func mount(request: Com_Apple_Containerization_Sandbox_V3_MountRequest, context: GRPC.GRPCAsyncServerCallContext)\n async throws -> Com_Apple_Containerization_Sandbox_V3_MountResponse\n {\n log.debug(\n \"mount\",\n metadata: [\n \"type\": \"\\(request.type)\",\n \"source\": \"\\(request.source)\",\n \"destination\": \"\\(request.destination)\",\n ])\n\n do {\n let mnt = ContainerizationOS.Mount(\n type: request.type,\n source: request.source,\n target: request.destination,\n options: request.options\n )\n\n #if os(Linux)\n try mnt.mount(createWithPerms: 0o755)\n return .init()\n #else\n fatalError(\"mount not supported on platform\")\n #endif\n } catch {\n log.error(\n \"mount\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"mount: \\(error)\")\n }\n }\n\n func umount(request: Com_Apple_Containerization_Sandbox_V3_UmountRequest, context: GRPC.GRPCAsyncServerCallContext)\n async throws -> Com_Apple_Containerization_Sandbox_V3_UmountResponse\n {\n log.debug(\n \"umount\",\n metadata: [\n \"path\": \"\\(request.path)\",\n \"flags\": \"\\(request.flags)\",\n ])\n\n #if os(Linux)\n // Best effort EBUSY handle.\n for _ in 0...50 {\n let result = _umount(request.path, request.flags)\n if result == -1 {\n if errno == EBUSY {\n try await Task.sleep(for: .milliseconds(10))\n continue\n }\n let error = swiftErrno(\"umount\")\n\n log.error(\n \"umount\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .invalidArgument, message: \"umount: \\(error)\")\n }\n break\n }\n return .init()\n #else\n fatalError(\"umount not supported on platform\")\n #endif\n }\n\n func setenv(request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest, context: GRPC.GRPCAsyncServerCallContext)\n async throws -> Com_Apple_Containerization_Sandbox_V3_SetenvResponse\n {\n log.debug(\n \"setenv\",\n metadata: [\n \"key\": \"\\(request.key)\",\n \"value\": \"\\(request.value)\",\n ])\n\n guard _setenv(request.key, request.value, 1) == 0 else {\n let error = swiftErrno(\"setenv\")\n\n log.error(\n \"setEnv\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n\n throw GRPCStatus(code: .invalidArgument, message: \"setenv: \\(error)\")\n }\n return .init()\n }\n\n func getenv(request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest, context: GRPC.GRPCAsyncServerCallContext)\n async throws -> Com_Apple_Containerization_Sandbox_V3_GetenvResponse\n {\n log.debug(\n \"getenv\",\n metadata: [\n \"key\": \"\\(request.key)\"\n ])\n\n let env = ProcessInfo.processInfo.environment[request.key]\n return .with {\n if let env {\n $0.value = env\n }\n }\n }\n\n func createProcess(\n request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest, context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse {\n log.debug(\n \"createProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"stdin\": \"Port: \\(request.stdin)\",\n \"stdout\": \"Port: \\(request.stdout)\",\n \"stderr\": \"Port: \\(request.stderr)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n do {\n var ociSpec = try JSONDecoder().decode(\n ContainerizationOCI.Spec.self,\n from: request.configuration\n )\n\n try ociAlterations(ociSpec: &ociSpec)\n\n guard let process = ociSpec.process else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"oci runtime spec missing process configuration\"\n )\n }\n\n let stdioPorts = HostStdio(\n stdin: request.hasStdin ? request.stdin : nil,\n stdout: request.hasStdout ? request.stdout : nil,\n stderr: request.hasStderr ? request.stderr : nil,\n terminal: process.terminal\n )\n\n // This is an exec.\n if let container = await self.state.containers[request.containerID] {\n try await container.createExec(\n id: request.id,\n stdio: stdioPorts,\n process: process\n )\n } else {\n // We need to make our new fangled container.\n // The process ID must match the container ID for this.\n guard request.id == request.containerID else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"init process id must match container id\"\n )\n }\n\n // Write the etc/hostname file in the container rootfs since some init-systems\n // depend on it.\n let hostname = ociSpec.hostname\n if let root = ociSpec.root, !hostname.isEmpty {\n let etc = URL(fileURLWithPath: root.path).appendingPathComponent(\"etc\")\n try FileManager.default.createDirectory(atPath: etc.path, withIntermediateDirectories: true)\n let hostnamePath = etc.appendingPathComponent(\"hostname\")\n try hostname.write(toFile: hostnamePath.path, atomically: true, encoding: .utf8)\n }\n\n let ctr = try ManagedContainer(\n id: request.id,\n stdio: stdioPorts,\n spec: ociSpec,\n log: self.log\n )\n try await self.state.add(container: ctr)\n }\n\n return .init()\n } catch {\n log.error(\n \"createProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"error\": \"\\(error)\",\n ])\n if error is GRPCStatus {\n throw error\n }\n throw GRPCStatus(code: .internalError, message: \"create managed process: \\(error)\")\n }\n }\n\n func killProcess(\n request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillProcessResponse {\n log.debug(\n \"killProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"signal\": \"\\(request.signal)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n let ctr = try await self.state.get(container: request.containerID)\n try await ctr.kill(execID: request.id, request.signal)\n\n return .init()\n }\n\n func deleteProcess(\n request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest, context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse {\n log.debug(\n \"deleteProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n let ctr = try await self.state.get(container: request.containerID)\n\n // Are we trying to delete the container itself?\n if request.id == request.containerID {\n try await ctr.delete()\n try await state.remove(container: request.id)\n } else {\n // Or just a single exec.\n try await ctr.deleteExec(id: request.id)\n }\n\n return .init()\n }\n\n func startProcess(\n request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest, context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StartProcessResponse {\n log.debug(\n \"startProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n do {\n let ctr = try await self.state.get(container: request.containerID)\n let pid = try await ctr.start(execID: request.id)\n\n return .with {\n $0.pid = pid\n }\n } catch {\n log.error(\n \"startProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"error\": \"\\(error)\",\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"startProcess: failed to start process: \\(error)\"\n )\n }\n }\n\n func resizeProcess(\n request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest, context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse {\n log.debug(\n \"resizeProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n do {\n let ctr = try await self.state.get(container: request.containerID)\n let size = Terminal.Size(\n width: UInt16(request.columns),\n height: UInt16(request.rows)\n )\n try await ctr.resize(execID: request.id, size: size)\n } catch {\n log.error(\n \"resizeProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"error\": \"\\(error)\",\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"resizeProcess: failed to resize process: \\(error)\"\n )\n }\n\n return .init()\n }\n\n func waitProcess(\n request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest, context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse {\n log.debug(\n \"waitProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n do {\n let ctr = try await self.state.get(container: request.containerID)\n\n let exitCode = try await ctr.wait(execID: request.id)\n\n return .with {\n $0.exitCode = exitCode\n }\n } catch {\n log.error(\n \"waitProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"error\": \"\\(error)\",\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"waitProcess: failed to wait on process: \\(error)\"\n )\n }\n }\n\n func closeProcessStdin(\n request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest, context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse {\n log.debug(\n \"closeProcessStdin\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n do {\n let ctr = try await self.state.get(container: request.containerID)\n\n try await ctr.closeStdin(execID: request.id)\n\n return .init()\n } catch {\n log.error(\n \"closeProcessStdin\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"error\": \"\\(error)\",\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"closeProcessStdin: failed to close process stdin: \\(error)\"\n )\n }\n }\n\n func ipLinkSet(\n request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest, context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse {\n log.debug(\n \"ip-link-set\",\n metadata: [\n \"interface\": \"\\(request.interface)\",\n \"up\": \"\\(request.up)\",\n ])\n\n do {\n let socket = try DefaultNetlinkSocket()\n let session = NetlinkSession(socket: socket, log: log)\n let mtuValue: UInt32? = request.hasMtu ? request.mtu : nil\n try session.linkSet(interface: request.interface, up: request.up, mtu: mtuValue)\n } catch {\n log.error(\n \"ip-link-set\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"ip-link-set: \\(error)\")\n }\n\n return .init()\n }\n\n func ipAddrAdd(\n request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest, context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse {\n log.debug(\n \"ip-addr-add\",\n metadata: [\n \"interface\": \"\\(request.interface)\",\n \"addr\": \"\\(request.address)\",\n ])\n\n do {\n let socket = try DefaultNetlinkSocket()\n let session = NetlinkSession(socket: socket, log: log)\n try session.addressAdd(interface: request.interface, address: request.address)\n } catch {\n log.error(\n \"ip-addr-add\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"ip-addr-add: \\(error)\")\n }\n\n return .init()\n }\n\n func ipRouteAddLink(\n request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest, context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse {\n log.debug(\n \"ip-route-add-link\",\n metadata: [\n \"interface\": \"\\(request.interface)\",\n \"address\": \"\\(request.address)\",\n \"srcAddr\": \"\\(request.srcAddr)\",\n ])\n\n do {\n let socket = try DefaultNetlinkSocket()\n let session = NetlinkSession(socket: socket, log: log)\n try session.routeAdd(\n interface: request.interface,\n destinationAddress: request.address,\n srcAddr: request.srcAddr\n )\n } catch {\n log.error(\n \"ip-route-add-link\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"ip-route-add-link: \\(error)\")\n }\n\n return .init()\n }\n\n func ipRouteAddDefault(\n request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse {\n log.debug(\n \"ip-route-add-default\",\n metadata: [\n \"interface\": \"\\(request.interface)\",\n \"gateway\": \"\\(request.gateway)\",\n ])\n\n do {\n let socket = try DefaultNetlinkSocket()\n let session = NetlinkSession(socket: socket, log: log)\n try session.routeAddDefault(interface: request.interface, gateway: request.gateway)\n } catch {\n log.error(\n \"ip-route-add-default\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"ip-route-add-default: \\(error)\")\n }\n\n return .init()\n }\n\n func configureDns(\n request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse {\n let domain = request.hasDomain ? request.domain : nil\n log.debug(\n \"configure-dns\",\n metadata: [\n \"location\": \"\\(request.location)\",\n \"nameservers\": \"\\(request.nameservers)\",\n \"domain\": \"\\(domain ?? \"\")\",\n ])\n\n do {\n let etc = URL(fileURLWithPath: request.location).appendingPathComponent(\"etc\")\n try FileManager.default.createDirectory(atPath: etc.path, withIntermediateDirectories: true)\n let resolvConf = etc.appendingPathComponent(\"resolv.conf\")\n let config = DNS(\n nameservers: request.nameservers,\n domain: domain,\n searchDomains: request.searchDomains,\n options: request.options\n )\n let text = config.resolvConf\n log.debug(\"writing to path \\(resolvConf.path) \\(text)\")\n try text.write(toFile: resolvConf.path, atomically: true, encoding: .utf8)\n log.debug(\"wrote resolver configuration\", metadata: [\"path\": \"\\(resolvConf.path)\"])\n } catch {\n log.error(\n \"configure-dns\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"configure-dns: \\(error)\")\n }\n\n return .init()\n }\n\n func configureHosts(\n request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse {\n log.debug(\n \"configureHosts\",\n metadata: [\n \"location\": \"\\(request.location)\"\n ])\n\n do {\n let etc = URL(fileURLWithPath: request.location).appendingPathComponent(\"etc\")\n try FileManager.default.createDirectory(atPath: etc.path, withIntermediateDirectories: true)\n let hostsPath = etc.appendingPathComponent(\"hosts\")\n\n let config = request.toCZHosts()\n let text = config.hostsFile\n try text.write(toFile: hostsPath.path, atomically: true, encoding: .utf8)\n\n log.debug(\"wrote /etc/hosts configuration\", metadata: [\"path\": \"\\(hostsPath.path)\"])\n } catch {\n log.error(\n \"configureHosts\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"configureHosts: \\(error)\")\n }\n\n return .init()\n }\n\n private func swiftErrno(_ msg: Logger.Message) -> POSIXError {\n let error = POSIXError(.init(rawValue: errno)!)\n log.error(\n msg,\n metadata: [\n \"error\": \"\\(error)\"\n ])\n return error\n }\n\n func sync(\n request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SyncResponse {\n log.debug(\"sync\")\n\n _sync()\n return .init()\n }\n\n func kill(\n request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillResponse {\n log.debug(\n \"kill\",\n metadata: [\n \"pid\": \"\\(request.pid)\",\n \"signal\": \"\\(request.signal)\",\n ])\n\n let r = _kill(request.pid, request.signal)\n return .with {\n $0.result = r\n }\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest {\n func toCZHosts() -> Hosts {\n let entries = self.entries.map {\n Hosts.Entry(\n ipAddress: $0.ipAddress,\n hostnames: $0.hostnames,\n comment: $0.hasComment ? $0.comment : nil\n )\n }\n return Hosts(\n entries: entries,\n comment: self.hasComment ? self.comment : nil\n )\n }\n}\n\nextension Initd {\n func ociAlterations(ociSpec: inout ContainerizationOCI.Spec) throws {\n guard var process = ociSpec.process else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"runtime spec without process field present\"\n )\n }\n guard let root = ociSpec.root else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"runtime spec without root field present\"\n )\n }\n\n if process.cwd.isEmpty {\n process.cwd = \"/\"\n }\n\n // Username is truthfully a Windows field, but we use this as away to pass through\n // the exact string representation of a username a client may have given us.\n let username = process.user.username.isEmpty ? \"\\(process.user.uid):\\(process.user.gid)\" : process.user.username\n let parsedUser = try User.parseUser(root: root.path, userString: username)\n process.user.uid = parsedUser.uid\n process.user.gid = parsedUser.gid\n process.user.additionalGids = parsedUser.sgids\n if !process.env.contains(where: { $0.hasPrefix(\"HOME=\") }) {\n process.env.append(\"HOME=\\(parsedUser.home)\")\n }\n\n // Defensive programming a tad, but ensure we have TERM set if\n // the client requested a pty.\n if process.terminal {\n let termEnv = \"TERM=\"\n if !process.env.contains(where: { $0.hasPrefix(termEnv) }) {\n process.env.append(\"TERM=xterm\")\n }\n }\n\n ociSpec.process = process\n }\n}\n"], ["/containerization/Sources/Integration/VMTests.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport Logging\n\nextension IntegrationSuite {\n func testMounts() async throws {\n let id = \"test-cat-mount\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n let directory = try createMountDirectory()\n config.process.arguments = [\"/bin/cat\", \"/mnt/hi.txt\"]\n config.mounts.append(.share(source: directory.path, destination: \"/mnt\"))\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n let value = String(data: buffer.data, encoding: .utf8)\n guard value == \"hello\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned from file 'hello' != '\\(String(data: buffer.data, encoding: .utf8)!)\")\n\n }\n }\n\n func testNestedVirtualizationEnabled() async throws {\n let id = \"test-nested-virt\"\n\n let bs = try await bootstrap()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/true\"]\n config.virtualization = true\n }\n\n do {\n try await container.create()\n try await container.start()\n } catch {\n if let err = error as? ContainerizationError {\n if err.code == .unsupported {\n throw SkipTest(reason: err.message)\n }\n }\n }\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n }\n\n func testContainerManagerCreate() async throws {\n let id = \"test-container-manager\"\n\n // Get the kernel from bootstrap\n let bs = try await bootstrap()\n\n // Create ContainerManager with kernel and initfs reference\n let manager = try ContainerManager(vmm: bs.vmm)\n defer {\n try? manager.delete(id)\n }\n\n let buffer = BufferWriter()\n let container = try await manager.create(\n id,\n image: bs.image,\n rootfs: bs.rootfs\n ) { config in\n config.process.arguments = [\"/bin/echo\", \"ContainerManager test\"]\n config.process.stdout = buffer\n }\n\n // Start the container\n try await container.create()\n try await container.start()\n\n // Wait for completion\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n let output = String(data: buffer.data, encoding: .utf8)\n guard output == \"ContainerManager test\\n\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned 'ContainerManager test' != '\\(output ?? \"nil\")'\")\n }\n }\n\n private func createMountDirectory() throws -> URL {\n let dir = FileManager.default.uniqueTemporaryDirectory(create: true)\n try \"hello\".write(to: dir.appendingPathComponent(\"hi.txt\"), atomically: true, encoding: .utf8)\n return dir\n }\n}\n"], ["/containerization/vminitd/Sources/vmexec/RunCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerizationOCI\nimport Foundation\nimport LCShim\nimport Logging\nimport Musl\n\nstruct RunCommand: ParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"run\",\n abstract: \"Run a container\"\n )\n\n @Option(name: .long, help: \"path to an OCI bundle\")\n var bundlePath: String\n\n mutating func run() throws {\n LoggingSystem.bootstrap(App.standardError)\n let log = Logger(label: \"vmexec\")\n\n let bundle = try ContainerizationOCI.Bundle.load(path: URL(filePath: bundlePath))\n let ociSpec = try bundle.loadConfig()\n try execInNamespace(spec: ociSpec, log: log)\n }\n\n private func childRootSetup(rootfs: ContainerizationOCI.Root, mounts: [ContainerizationOCI.Mount], log: Logger) throws {\n // setup rootfs\n try prepareRoot(rootfs: rootfs.path)\n try mountRootfs(rootfs: rootfs.path, mounts: mounts)\n try setDevSymlinks(rootfs: rootfs.path)\n\n try pivotRoot(rootfs: rootfs.path)\n try reOpenDevNull()\n }\n\n private func execInNamespace(spec: ContainerizationOCI.Spec, log: Logger) throws {\n guard let process = spec.process else {\n fatalError(\"no process configuration found in runtime spec\")\n }\n guard let root = spec.root else {\n fatalError(\"no root found in runtime spec\")\n }\n\n let syncfd = FileHandle(fileDescriptor: 3)\n if fcntl(3, F_SETFD, FD_CLOEXEC) == -1 {\n throw App.Errno(stage: \"cloexec(syncfd)\")\n }\n\n guard unshare(CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWUTS) == 0 else {\n throw App.Errno(stage: \"unshare(pid|mnt|uts)\")\n }\n\n let childPipe = Pipe()\n try childPipe.setCloexec()\n let processID = fork()\n\n guard processID != -1 else {\n try? childPipe.fileHandleForReading.close()\n try? childPipe.fileHandleForWriting.close()\n try? syncfd.close()\n\n throw App.Errno(stage: \"fork\")\n }\n\n if processID == 0 { // child\n try childPipe.fileHandleForReading.close()\n try syncfd.close()\n\n guard unshare(CLONE_NEWCGROUP) == 0 else {\n throw App.Errno(stage: \"unshare(cgroup)\")\n }\n\n guard setsid() != -1 else {\n throw App.Errno(stage: \"setsid()\")\n }\n\n try childRootSetup(rootfs: root, mounts: spec.mounts, log: log)\n\n if !spec.hostname.isEmpty {\n let errCode = spec.hostname.withCString { ptr in\n Musl.sethostname(ptr, spec.hostname.count)\n }\n guard errCode == 0 else {\n throw App.Errno(stage: \"sethostname()\")\n }\n }\n\n // Apply O_CLOEXEC to all file descriptors except stdio.\n // This ensures that all unwanted fds we may have accidentally\n // inherited are marked close-on-exec so they stay out of the\n // container.\n try App.applyCloseExecOnFDs()\n\n try App.setRLimits(rlimits: process.rlimits)\n\n // Change stdio to be owned by the requested user.\n try App.fixStdioPerms(user: process.user)\n\n // Set uid, gid, and supplementary groups.\n try App.setPermissions(user: process.user)\n\n if process.terminal {\n guard ioctl(0, UInt(TIOCSCTTY), 0) != -1 else {\n throw App.Errno(stage: \"setctty()\")\n }\n }\n\n try App.exec(process: process)\n } else { // parent process\n try childPipe.fileHandleForWriting.close()\n\n // wait until the pipe is closed then carry on.\n _ = try childPipe.fileHandleForReading.readToEnd()\n try childPipe.fileHandleForReading.close()\n\n // send our child's pid to our parent before we exit.\n var childPid = processID\n let data = Data(bytes: &childPid, count: MemoryLayout.size(ofValue: childPid))\n\n try syncfd.write(contentsOf: data)\n try syncfd.close()\n }\n }\n\n private func mountRootfs(rootfs: String, mounts: [ContainerizationOCI.Mount]) throws {\n let containerMount = ContainerMount(rootfs: rootfs, mounts: mounts)\n try containerMount.mountToRootfs()\n try containerMount.configureConsole()\n }\n\n private func prepareRoot(rootfs: String) throws {\n guard mount(\"\", \"/\", \"\", UInt(MS_SLAVE | MS_REC), nil) == 0 else {\n throw App.Errno(stage: \"mount(slave|rec)\")\n }\n\n guard mount(rootfs, rootfs, \"bind\", UInt(MS_BIND | MS_REC), nil) == 0 else {\n throw App.Errno(stage: \"mount(bind|rec)\")\n }\n }\n\n private func setDevSymlinks(rootfs: String) throws {\n let links: [(src: String, dst: String)] = [\n (\"/proc/self/fd\", \"/dev/fd\"),\n (\"/proc/self/fd/0\", \"/dev/stdin\"),\n (\"/proc/self/fd/1\", \"/dev/stdout\"),\n (\"/proc/self/fd/2\", \"/dev/stderr\"),\n ]\n\n let rootfsURL = URL(fileURLWithPath: rootfs)\n for (src, dst) in links {\n let dest = rootfsURL.appendingPathComponent(dst)\n guard symlink(src, dest.path) == 0 else {\n if errno == EEXIST {\n continue\n }\n throw App.Errno(stage: \"symlink()\")\n }\n }\n }\n\n private func reOpenDevNull() throws {\n let file = open(\"/dev/null\", O_RDWR)\n guard file != -1 else {\n throw App.Errno(stage: \"open(/dev/null)\")\n }\n defer { close(file) }\n\n var devNullStat = stat()\n try withUnsafeMutablePointer(to: &devNullStat) { pointer in\n guard fstat(file, pointer) == 0 else {\n throw App.Errno(stage: \"fstat(/dev/null)\")\n }\n }\n\n for fd: Int32 in 0...2 {\n var fdStat = stat()\n try withUnsafeMutablePointer(to: &fdStat) { pointer in\n guard fstat(fd, pointer) == 0 else {\n throw App.Errno(stage: \"fstat(fd)\")\n }\n }\n\n if fdStat.st_rdev == devNullStat.st_rdev {\n guard dup3(file, fd, 0) != -1 else {\n throw App.Errno(stage: \"dup3(null)\")\n }\n }\n }\n }\n\n /// Pivots the rootfs of the calling process in the namespace to the provided\n /// rootfs in the argument.\n ///\n /// The pivot_root(\".\", \".\") and unmount old root approach is exactly the same\n /// as runc's pivot root implementation in:\n /// https://github.com/opencontainers/runc/blob/main/libcontainer/rootfs_linux.go\n private func pivotRoot(rootfs: String) throws {\n let oldRoot = open(\"/\", O_RDONLY | O_DIRECTORY)\n if oldRoot <= 0 {\n throw App.Errno(stage: \"open(oldroot)\")\n }\n defer { close(oldRoot) }\n\n let newRoot = open(rootfs, O_RDONLY | O_DIRECTORY)\n if newRoot <= 0 {\n throw App.Errno(stage: \"open(newroot)\")\n }\n\n defer { close(newRoot) }\n\n // change cwd to the new root\n guard fchdir(newRoot) == 0 else {\n throw App.Errno(stage: \"fchdir(newroot)\")\n }\n guard CZ_pivot_root(toCString(\".\"), toCString(\".\")) == 0 else {\n throw App.Errno(stage: \"pivot_root()\")\n }\n // change cwd to the old root\n guard fchdir(oldRoot) == 0 else {\n throw App.Errno(stage: \"fchdir(oldroot)\")\n }\n // mount old root rslave so that unmount doesn't propagate back to outside\n // the namespace\n guard mount(\"\", \".\", \"\", UInt(MS_SLAVE | MS_REC), nil) == 0 else {\n throw App.Errno(stage: \"mount(., slave|rec)\")\n }\n // unmount old root\n guard umount2(\".\", Int32(MNT_DETACH)) == 0 else {\n throw App.Errno(stage: \"umount(.)\")\n }\n // switch cwd to the new root\n guard chdir(\"/\") == 0 else {\n throw App.Errno(stage: \"chdir(/)\")\n }\n }\n\n private func toCString(_ str: String) -> UnsafeMutablePointer? {\n let cString = str.utf8CString\n let cStringCopy = UnsafeMutableBufferPointer.allocate(capacity: cString.count)\n _ = cStringCopy.initialize(from: cString)\n return UnsafeMutablePointer(cStringCopy.baseAddress)\n }\n}\n"], ["/containerization/Sources/cctl/LoginCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\nextension Application {\n struct Login: AsyncParsableCommand {\n\n static let configuration = CommandConfiguration(\n commandName: \"login\",\n abstract: \"Login to a registry\"\n )\n\n @OptionGroup() var application: Application\n\n @Option(name: .shortAndLong, help: \"Username\")\n var username: String = \"\"\n\n @Flag(help: \"Take the password from stdin\")\n var passwordStdin: Bool = false\n\n @Argument(help: \"Registry server name\")\n var server: String\n\n @Flag(help: \"Use plain text http to authenticate\") var http: Bool = false\n\n func run() async throws {\n var username = self.username\n var password = \"\"\n if passwordStdin {\n if username == \"\" {\n throw ContainerizationError(.invalidArgument, message: \"must provide --username with --password-stdin\")\n }\n guard let passwordData = try FileHandle.standardInput.readToEnd() else {\n throw ContainerizationError(.invalidArgument, message: \"failed to read password from stdin\")\n }\n password = String(decoding: passwordData, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)\n }\n let keychain = KeychainHelper(id: Application.keychainID)\n if username == \"\" {\n username = try keychain.userPrompt(domain: server)\n }\n if password == \"\" {\n password = try keychain.passwordPrompt()\n print()\n }\n\n let server = Reference.resolveDomain(domain: self.server)\n let scheme = http ? \"http\" : \"https\"\n let client = RegistryClient(\n host: server,\n scheme: scheme,\n authentication: BasicAuthentication(username: username, password: password),\n retryOptions: .init(\n maxRetries: 10,\n retryInterval: 300_000_000,\n shouldRetry: ({ response in\n response.status.code >= 500\n })\n )\n )\n try await client.ping()\n try keychain.save(domain: server, username: username, password: password)\n print(\"Login succeeded\")\n }\n }\n}\n"], ["/containerization/Sources/Containerization/Image/ImageStore/ImageStore+Import.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\nextension ImageStore {\n internal struct ImportOperation {\n static let decoder = JSONDecoder()\n\n let client: ContentClient\n let ingestDir: URL\n let contentStore: ContentStore\n let progress: ProgressHandler?\n let name: String\n\n init(name: String, contentStore: ContentStore, client: ContentClient, ingestDir: URL, progress: ProgressHandler? = nil) {\n self.client = client\n self.ingestDir = ingestDir\n self.contentStore = contentStore\n self.progress = progress\n self.name = name\n }\n\n /// Pull the required image layers for the provided descriptor and platform(s) into the given directory using the provided client. Returns a descriptor to the Index manifest.\n internal func `import`(root: Descriptor, matcher: (ContainerizationOCI.Platform) -> Bool) async throws -> Descriptor {\n var toProcess = [root]\n while !toProcess.isEmpty {\n // Count the total number of blobs and their size\n if let progress {\n var size: Int64 = 0\n for desc in toProcess {\n size += desc.size\n }\n await progress([\n ProgressEvent(event: \"add-total-size\", value: size),\n ProgressEvent(event: \"add-total-items\", value: toProcess.count),\n ])\n }\n\n try await self.fetchAll(toProcess)\n let children = try await self.walk(toProcess)\n let filtered = try filterPlatforms(matcher: matcher, children)\n toProcess = filtered.uniqued { $0.digest }\n }\n\n guard root.mediaType != MediaTypes.dockerManifestList && root.mediaType != MediaTypes.index else {\n return root\n }\n\n // Create an index for the root descriptor and write it to the content store\n let index = try await self.createIndex(for: root)\n // In cases where the root descriptor pointed to `MediaTypes.imageManifest`\n // Or `MediaTypes.dockerManifest`, it is required that we check the supported platform\n // matches the platforms we were asked to pull. This can be done only after we created\n // the Index.\n let supportedPlatforms = index.manifests.compactMap { $0.platform }\n guard supportedPlatforms.allSatisfy(matcher) else {\n throw ContainerizationError(.unsupported, message: \"Image \\(root.digest) does not support required platforms\")\n }\n let writer = try ContentWriter(for: self.ingestDir)\n let result = try writer.create(from: index)\n return Descriptor(\n mediaType: MediaTypes.index,\n digest: result.digest.digestString,\n size: Int64(result.size))\n }\n\n private func getManifestContent(descriptor: Descriptor) async throws -> T {\n do {\n if let content = try await self.contentStore.get(digest: descriptor.digest.trimmingDigestPrefix) {\n return try content.decode()\n }\n if let content = try? LocalContent(path: ingestDir.appending(path: descriptor.digest.trimmingDigestPrefix)) {\n return try content.decode()\n }\n return try await self.client.fetch(name: name, descriptor: descriptor)\n } catch {\n throw ContainerizationError(.internalError, message: \"Cannot fetch content with digest \\(descriptor.digest)\", cause: error)\n }\n }\n\n private func walk(_ descriptors: [Descriptor]) async throws -> [Descriptor] {\n var out: [Descriptor] = []\n for desc in descriptors {\n let mediaType = desc.mediaType\n switch mediaType {\n case MediaTypes.index, MediaTypes.dockerManifestList:\n let index: Index = try await self.getManifestContent(descriptor: desc)\n out.append(contentsOf: index.manifests)\n case MediaTypes.imageManifest, MediaTypes.dockerManifest:\n let manifest: Manifest = try await self.getManifestContent(descriptor: desc)\n out.append(manifest.config)\n out.append(contentsOf: manifest.layers)\n default:\n // TODO: Explicitly handle other content types\n continue\n }\n }\n return out\n }\n\n private func fetchAll(_ descriptors: [Descriptor]) async throws {\n try await withThrowingTaskGroup(of: Void.self) { group in\n var iterator = descriptors.makeIterator()\n for _ in 0..<8 {\n if let desc = iterator.next() {\n group.addTask {\n try await fetch(desc)\n }\n }\n }\n for try await _ in group {\n if let desc = iterator.next() {\n group.addTask {\n try await fetch(desc)\n }\n }\n }\n }\n }\n\n private func fetch(_ descriptor: Descriptor) async throws {\n if let found = try await self.contentStore.get(digest: descriptor.digest) {\n try FileManager.default.copyItem(at: found.path, to: ingestDir.appendingPathComponent(descriptor.digest.trimmingDigestPrefix))\n await progress?([\n // Count the size of the blob\n ProgressEvent(event: \"add-size\", value: descriptor.size),\n // Count the number of blobs\n ProgressEvent(event: \"add-items\", value: 1),\n ])\n return\n }\n\n if descriptor.size > 1.mib() {\n try await self.fetchBlob(descriptor)\n } else {\n try await self.fetchData(descriptor)\n }\n // Count the number of blobs\n await progress?([\n ProgressEvent(event: \"add-items\", value: 1)\n ])\n }\n\n private func fetchBlob(_ descriptor: Descriptor) async throws {\n let id = UUID().uuidString\n let fm = FileManager.default\n let tempFile = ingestDir.appendingPathComponent(id)\n let (_, digest) = try await client.fetchBlob(name: name, descriptor: descriptor, into: tempFile, progress: progress)\n guard digest.digestString == descriptor.digest else {\n throw ContainerizationError(.internalError, message: \"Digest mismatch expected \\(descriptor.digest), got \\(digest.digestString)\")\n }\n do {\n try fm.moveItem(at: tempFile, to: ingestDir.appendingPathComponent(digest.encoded))\n } catch let err as NSError {\n guard err.code == NSFileWriteFileExistsError else {\n throw err\n }\n try fm.removeItem(at: tempFile)\n }\n }\n\n @discardableResult\n private func fetchData(_ descriptor: Descriptor) async throws -> Data {\n let data = try await client.fetchData(name: name, descriptor: descriptor)\n let writer = try ContentWriter(for: ingestDir)\n let result = try writer.write(data)\n if let progress {\n let size = Int64(result.size)\n await progress([\n ProgressEvent(event: \"add-size\", value: size)\n ])\n }\n guard result.digest.digestString == descriptor.digest else {\n throw ContainerizationError(.internalError, message: \"Digest mismatch expected \\(descriptor.digest), got \\(result.digest.digestString)\")\n }\n return data\n }\n\n private func createIndex(for root: Descriptor) async throws -> Index {\n switch root.mediaType {\n case MediaTypes.index, MediaTypes.dockerManifestList:\n return try await self.getManifestContent(descriptor: root)\n case MediaTypes.imageManifest, MediaTypes.dockerManifest:\n let supportedPlatforms = try await getSupportedPlatforms(for: root)\n guard supportedPlatforms.count == 1 else {\n throw ContainerizationError(\n .internalError,\n message:\n \"Descriptor \\(root.mediaType) with digest \\(root.digest) does not list any supported platform or supports more than one platform. Supported platforms = \\(supportedPlatforms)\"\n )\n }\n let platform = supportedPlatforms.first!\n var root = root\n root.platform = platform\n let index = ContainerizationOCI.Index(\n schemaVersion: 2, manifests: [root],\n annotations: [\n // indicate that this is a synthesized index which is not directly user facing\n AnnotationKeys.containerizationIndexIndirect: \"true\"\n ])\n return index\n default:\n throw ContainerizationError(.internalError, message: \"Failed to create index for descriptor \\(root.digest), media type \\(root.mediaType)\")\n }\n }\n\n private func getSupportedPlatforms(for root: Descriptor) async throws -> [ContainerizationOCI.Platform] {\n var supportedPlatforms: [ContainerizationOCI.Platform] = []\n var toProcess = [root]\n while !toProcess.isEmpty {\n let children = try await self.walk(toProcess)\n for child in children {\n if let p = child.platform {\n supportedPlatforms.append(p)\n continue\n }\n switch child.mediaType {\n case MediaTypes.imageConfig, MediaTypes.dockerImageConfig:\n let config: ContainerizationOCI.Image = try await self.getManifestContent(descriptor: child)\n let p = ContainerizationOCI.Platform(\n arch: config.architecture, os: config.os, osFeatures: config.osFeatures, variant: config.variant\n )\n supportedPlatforms.append(p)\n default:\n continue\n }\n }\n toProcess = children\n }\n return supportedPlatforms\n }\n\n }\n}\n"], ["/containerization/vminitd/Sources/vmexec/ExecCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerizationOCI\nimport Foundation\nimport LCShim\nimport Logging\nimport Musl\n\nstruct ExecCommand: ParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"exec\",\n abstract: \"Exec in a container\"\n )\n\n @Option(name: .long, help: \"path to an OCI runtime spec process configuration\")\n var processPath: String\n\n @Option(name: .long, help: \"pid of the init process for the container\")\n var parentPid: Int\n\n func run() throws {\n LoggingSystem.bootstrap(App.standardError)\n let log = Logger(label: \"vmexec\")\n\n let src = URL(fileURLWithPath: processPath)\n let processBytes = try Data(contentsOf: src)\n let process = try JSONDecoder().decode(\n ContainerizationOCI.Process.self,\n from: processBytes\n )\n try execInNamespaces(process: process, log: log)\n }\n\n static func enterNS(path: String, nsType: Int32) throws {\n let fd = open(path, O_RDONLY)\n if fd <= 0 {\n throw App.Errno(stage: \"open(ns)\")\n }\n defer { close(fd) }\n\n guard setns(fd, nsType) == 0 else {\n throw App.Errno(stage: \"setns(fd)\")\n }\n }\n\n private func execInNamespaces(\n process: ContainerizationOCI.Process,\n log: Logger\n ) throws {\n // CLOEXEC the pipe fd that signals process readiness.\n let syncfd = FileHandle(fileDescriptor: 3)\n if fcntl(3, F_SETFD, FD_CLOEXEC) == -1 {\n throw App.Errno(stage: \"cloexec(syncfd)\")\n }\n\n try Self.enterNS(path: \"/proc/\\(self.parentPid)/ns/cgroup\", nsType: CLONE_NEWCGROUP)\n try Self.enterNS(path: \"/proc/\\(self.parentPid)/ns/pid\", nsType: CLONE_NEWPID)\n try Self.enterNS(path: \"/proc/\\(self.parentPid)/ns/uts\", nsType: CLONE_NEWUTS)\n try Self.enterNS(path: \"/proc/\\(self.parentPid)/ns/mnt\", nsType: CLONE_NEWNS)\n\n let childPipe = Pipe()\n try childPipe.setCloexec()\n let processID = fork()\n\n guard processID != -1 else {\n try? childPipe.fileHandleForReading.close()\n try? childPipe.fileHandleForWriting.close()\n try? syncfd.close()\n\n throw App.Errno(stage: \"fork\")\n }\n\n if processID == 0 { // child\n try childPipe.fileHandleForReading.close()\n try syncfd.close()\n\n guard setsid() != -1 else {\n throw App.Errno(stage: \"setsid()\")\n }\n\n // Apply O_CLOEXEC to all file descriptors except stdio.\n // This ensures that all unwanted fds we may have accidentally\n // inherited are marked close-on-exec so they stay out of the\n // container.\n try App.applyCloseExecOnFDs()\n try App.setRLimits(rlimits: process.rlimits)\n\n // Change stdio to be owned by the requested user.\n try App.fixStdioPerms(user: process.user)\n\n // Set uid, gid, and supplementary groups\n try App.setPermissions(user: process.user)\n\n if process.terminal {\n guard ioctl(0, UInt(TIOCSCTTY), 0) != -1 else {\n throw App.Errno(stage: \"setctty()\")\n }\n }\n\n try App.exec(process: process)\n } else { // parent process\n try childPipe.fileHandleForWriting.close()\n\n // wait until the pipe is closed then carry on.\n _ = try childPipe.fileHandleForReading.readToEnd()\n try childPipe.fileHandleForReading.close()\n\n // send our child's pid to our parent before we exit.\n var childPid = processID\n let data = Data(bytes: &childPid, count: MemoryLayout.size(ofValue: childPid))\n\n try syncfd.write(contentsOf: data)\n try syncfd.close()\n }\n }\n}\n"], ["/containerization/Sources/Containerization/LinuxProcess.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport Synchronization\n\n/// `LinuxProcess` represents a Linux process and is used to\n/// setup and control the full lifecycle for the process.\npublic final class LinuxProcess: Sendable {\n /// The ID of the process. This is purely metadata for the caller.\n public let id: String\n\n /// What container owns this process (if any).\n public let owningContainer: String?\n\n package struct StdioSetup: Sendable {\n let port: UInt32\n let writer: Writer\n }\n\n package struct StdioReaderSetup {\n let port: UInt32\n let reader: ReaderStream\n }\n\n package struct Stdio: Sendable {\n let stdin: StdioReaderSetup?\n let stdout: StdioSetup?\n let stderr: StdioSetup?\n }\n\n private struct StdioHandles: Sendable {\n var stdin: FileHandle?\n var stdout: FileHandle?\n var stderr: FileHandle?\n\n mutating func close() throws {\n if let stdin {\n try stdin.close()\n stdin.readabilityHandler = nil\n self.stdin = nil\n }\n if let stdout {\n try stdout.close()\n stdout.readabilityHandler = nil\n self.stdout = nil\n }\n if let stderr {\n try stderr.close()\n stderr.readabilityHandler = nil\n self.stderr = nil\n }\n }\n }\n\n private struct State {\n var spec: ContainerizationOCI.Spec\n var pid: Int32\n var stdio: StdioHandles\n var stdinRelay: Task<(), Never>?\n var ioTracker: IoTracker?\n\n struct IoTracker {\n let stream: AsyncStream\n let cont: AsyncStream.Continuation\n let configuredStreams: Int\n }\n }\n\n /// The process ID for the container process. This will be -1\n /// if the process has not been started.\n public var pid: Int32 {\n state.withLock { $0.pid }\n }\n\n private let state: Mutex\n private let ioSetup: Stdio\n private let agent: any VirtualMachineAgent\n private let vm: any VirtualMachineInstance\n private let logger: Logger?\n\n init(\n _ id: String,\n containerID: String? = nil,\n spec: Spec,\n io: Stdio,\n agent: any VirtualMachineAgent,\n vm: any VirtualMachineInstance,\n logger: Logger?\n ) {\n self.id = id\n self.owningContainer = containerID\n self.state = Mutex(.init(spec: spec, pid: -1, stdio: StdioHandles()))\n self.ioSetup = io\n self.agent = agent\n self.vm = vm\n self.logger = logger\n }\n}\n\nextension LinuxProcess {\n func setupIO(streams: [VsockConnectionStream?]) async throws -> [FileHandle?] {\n let handles = try await Timeout.run(seconds: 3) {\n await withTaskGroup(of: (Int, FileHandle?).self) { group in\n var results = [FileHandle?](repeating: nil, count: 3)\n\n for (index, stream) in streams.enumerated() {\n guard let stream = stream else { continue }\n\n group.addTask {\n let first = await stream.connections.first(where: { _ in true })\n return (index, first)\n }\n }\n\n for await (index, fileHandle) in group {\n results[index] = fileHandle\n }\n return results\n }\n }\n\n if let stdin = self.ioSetup.stdin {\n if let handle = handles[0] {\n self.state.withLock {\n $0.stdinRelay = Task {\n for await data in stdin.reader.stream() {\n do {\n try handle.write(contentsOf: data)\n } catch {\n self.logger?.error(\"failed to write to stdin: \\(error)\")\n break\n }\n }\n\n do {\n self.logger?.debug(\"stdin relay finished, closing\")\n\n // There's two ways we can wind up here:\n //\n // 1. The stream finished on its own (e.g. we wrote all the\n // data) and we will close the underlying stdin in the guest below.\n //\n // 2. The client explicitly called closeStdin() themselves\n // which will cancel this relay task AFTER actually closing\n // the fds. If the client did that, then this task will be\n // cancelled, and the fds are already gone so there's nothing\n // for us to do.\n if Task.isCancelled {\n return\n }\n\n try await self._closeStdin()\n } catch {\n self.logger?.error(\"failed to close stdin: \\(error)\")\n }\n }\n }\n }\n }\n\n var configuredStreams = 0\n let (stream, cc) = AsyncStream.makeStream()\n if let stdout = self.ioSetup.stdout {\n configuredStreams += 1\n handles[1]?.readabilityHandler = { handle in\n do {\n let data = handle.availableData\n if data.isEmpty {\n // This block is called when the producer (the guest) closes\n // the fd it is writing into.\n handles[1]?.readabilityHandler = nil\n cc.yield()\n return\n }\n try stdout.writer.write(data)\n } catch {\n self.logger?.error(\"failed to write to stdout: \\(error)\")\n }\n }\n }\n\n if let stderr = self.ioSetup.stderr {\n configuredStreams += 1\n handles[2]?.readabilityHandler = { handle in\n do {\n let data = handle.availableData\n if data.isEmpty {\n handles[2]?.readabilityHandler = nil\n cc.yield()\n return\n }\n try stderr.writer.write(data)\n } catch {\n self.logger?.error(\"failed to write to stderr: \\(error)\")\n }\n }\n }\n if configuredStreams > 0 {\n self.state.withLock {\n $0.ioTracker = .init(stream: stream, cont: cc, configuredStreams: configuredStreams)\n }\n }\n\n return handles\n }\n\n /// Start the process.\n public func start() async throws {\n do {\n let spec = self.state.withLock { $0.spec }\n var streams = [VsockConnectionStream?](repeating: nil, count: 3)\n if let stdin = self.ioSetup.stdin {\n streams[0] = try self.vm.listen(stdin.port)\n }\n if let stdout = self.ioSetup.stdout {\n streams[1] = try self.vm.listen(stdout.port)\n }\n if let stderr = self.ioSetup.stderr {\n if spec.process!.terminal {\n throw ContainerizationError(\n .invalidArgument,\n message: \"stderr should not be configured with terminal=true\"\n )\n }\n streams[2] = try self.vm.listen(stderr.port)\n }\n\n let t = Task {\n try await self.setupIO(streams: streams)\n }\n\n try await agent.createProcess(\n id: self.id,\n containerID: self.owningContainer,\n stdinPort: self.ioSetup.stdin?.port,\n stdoutPort: self.ioSetup.stdout?.port,\n stderrPort: self.ioSetup.stderr?.port,\n configuration: spec,\n options: nil\n )\n\n let result = try await t.value\n let pid = try await self.agent.startProcess(\n id: self.id,\n containerID: self.owningContainer\n )\n\n self.state.withLock {\n $0.stdio = StdioHandles(\n stdin: result[0],\n stdout: result[1],\n stderr: result[2]\n )\n $0.pid = pid\n }\n } catch {\n if let err = error as? ContainerizationError {\n throw err\n }\n throw ContainerizationError(\n .internalError,\n message: \"failed to start process\",\n cause: error,\n )\n }\n }\n\n /// Kill the process with the specified signal.\n public func kill(_ signal: Int32) async throws {\n do {\n try await agent.signalProcess(\n id: self.id,\n containerID: self.owningContainer,\n signal: signal\n )\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to kill process\",\n cause: error\n )\n }\n }\n\n /// Resize the processes pty (if requested).\n public func resize(to: Terminal.Size) async throws {\n do {\n try await agent.resizeProcess(\n id: self.id,\n containerID: self.owningContainer,\n columns: UInt32(to.width),\n rows: UInt32(to.height)\n )\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to resize process\",\n cause: error\n )\n }\n }\n\n public func closeStdin() async throws {\n do {\n try await self._closeStdin()\n self.state.withLock {\n $0.stdinRelay?.cancel()\n }\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to close stdin\",\n cause: error,\n )\n }\n }\n\n func _closeStdin() async throws {\n try await self.agent.closeProcessStdin(\n id: self.id,\n containerID: self.owningContainer\n )\n }\n\n /// Wait on the process to exit with an optional timeout. Returns the exit code of the process.\n @discardableResult\n public func wait(timeoutInSeconds: Int64? = nil) async throws -> Int32 {\n do {\n let code = try await self.agent.waitProcess(\n id: self.id,\n containerID: self.owningContainer,\n timeoutInSeconds: timeoutInSeconds\n )\n await self.waitIoComplete()\n return code\n } catch {\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(\n .internalError,\n message: \"failed to wait on process\",\n cause: error\n )\n }\n }\n\n /// Wait until the standard output and standard error streams for the process have concluded.\n private func waitIoComplete() async {\n let ioTracker = self.state.withLock { $0.ioTracker }\n guard let ioTracker else {\n return\n }\n do {\n try await Timeout.run(seconds: 3) {\n var counter = ioTracker.configuredStreams\n for await _ in ioTracker.stream {\n counter -= 1\n if counter == 0 {\n ioTracker.cont.finish()\n break\n }\n }\n }\n } catch {\n self.logger?.error(\"Timeout waiting for IO to complete for process \\(id): \\(error)\")\n }\n self.state.withLock {\n $0.ioTracker = nil\n }\n }\n\n /// Cleans up guest state and waits on and closes any host resources (stdio handles).\n public func delete() async throws {\n do {\n try await self.agent.deleteProcess(\n id: self.id,\n containerID: self.owningContainer\n )\n } catch {\n self.logger?.error(\n \"process deletion\",\n metadata: [\n \"id\": \"\\(self.id)\",\n \"error\": \"\\(error)\",\n ])\n }\n\n do {\n try self.state.withLock {\n $0.stdinRelay?.cancel()\n try $0.stdio.close()\n }\n } catch {\n self.logger?.error(\n \"closing process stdio\",\n metadata: [\n \"id\": \"\\(self.id)\",\n \"error\": \"\\(error)\",\n ])\n }\n\n do {\n try await self.agent.close()\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to close agent connection\",\n cause: error,\n )\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Formatter.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// swiftlint: disable discouraged_direct_init shorthand_operator syntactic_sugar\n\nimport ContainerizationOS\nimport Foundation\nimport SystemPackage\n\nextension EXT4 {\n /// The `EXT4.Formatter` class provides methods to format a block device with the ext4 filesystem.\n /// It allows customization of block size and maximum disk size.\n public class Formatter {\n private let blockSize: UInt32\n private var size: UInt64\n private let groupDescriptorSize: UInt32 = 32\n\n private var blocksPerGroup: UInt32 {\n blockSize * 8\n }\n\n private var maxInodesPerGroup: UInt32 {\n blockSize * 8 // limited by inode bitmap\n }\n\n private var groupsPerDescriptorBlock: UInt32 {\n blockSize / groupDescriptorSize\n }\n\n private var blockCount: UInt32 {\n ((size - 1) / blockSize) + 1\n }\n\n private var groupCount: UInt32 {\n (blockCount - 1) / blocksPerGroup + 1\n }\n\n private var groupDescriptorBlocks: UInt32 {\n ((groupCount - 1) / groupsPerDescriptorBlock + 1) * 32\n }\n\n /// Initializes an ext4 filesystem formatter.\n ///\n /// This constructor creates an instance of the ext4 formatter designed to format a block device\n /// with the ext4 filesystem. The formatter takes the path to the destination block device and\n /// the desired block size of the filesystem as parameters.\n ///\n /// - Parameters:\n /// - devicePath: The path to the block device where the ext4 filesystem will be created.\n /// - blockSize: The block size of the ext4 filesystem, specified in bytes. Common values are\n /// 4096 (4KB) or 1024 (1KB). Default is 4096 (4KB)\n /// - minDiskSize: The minimum disk size required for the formatted filesystem.\n ///\n /// - Note: This ext4 formatter is designed for creating block devices out of container images and does not support all the\n /// features and options available in the full ext4 filesystem implementation. It focuses\n /// on the core functionality required for formatting a block device with ext4.\n ///\n /// - Important: Ensure that the destination block device is accessible and has sufficient permissions\n /// for formatting. The formatting process will erase all existing data on the device.\n public init(_ devicePath: FilePath, blockSize: UInt32 = 4096, minDiskSize: UInt64 = 256.kib()) throws {\n /// The constructor performs the following steps:\n ///\n /// 1. Creates the first 10 inodes:\n /// - Inode 2 is reserved for the root directory ('/').\n /// - Inodes 1 and 3-10 are reserved for other special purposes.\n ///\n /// 2. Marks inode 11 as the first inode available for consumption by files, directories, sockets,\n /// FIFOs, etc.\n ///\n /// 3. Initializes a directory tree with the root directory pointing to inode 2.\n ///\n /// 4. Moves the file descriptor to the start of the block where file metadata and data can be\n /// written, which is located past the filesystem superblocks and group descriptor blocks.\n ///\n /// 5. Creates a \"/lost+found\" directory to satisfy the requirements of e2fsck (ext2/3/4 filesystem\n /// checker).\n\n if !FileManager.default.fileExists(atPath: devicePath.description) {\n FileManager.default.createFile(atPath: devicePath.description, contents: nil)\n }\n guard let fileHandle = FileHandle(forWritingTo: devicePath) else {\n throw Error.notFound(devicePath)\n }\n self.handle = fileHandle\n self.blockSize = blockSize\n self.size = minDiskSize\n // make this a 0 byte file\n guard ftruncate(self.handle.fileDescriptor, 0) == 0 else {\n throw Error.cannotTruncateFile(devicePath)\n }\n // make it a sparse file\n guard lseek(self.handle.fileDescriptor, off_t(self.size - 1), 0) == self.size - 1 else {\n throw Error.cannotCreateSparseFile(devicePath)\n }\n let zero: [UInt8] = [0]\n try self.handle.write(contentsOf: zero)\n // step #1\n self.inodes = [\n Ptr.allocate(capacity: 1), // defective block inode\n {\n let root = Inode.Root()\n let rootPtr = Ptr.allocate(capacity: 1)\n rootPtr.initialize(to: root)\n return rootPtr\n }(),\n ]\n // reserved inodes\n for _ in 2...allocate(capacity: 1))\n }\n // step #2\n self.tree = FileTree(EXT4.RootInode, \"/\")\n // skip past the superblock and block descriptor table\n try self.seek(block: self.groupDescriptorBlocks + 1)\n // lost+found directory is required for e2fsck to pass\n try self.create(path: FilePath(\"/lost+found\"), mode: Inode.Mode(.S_IFDIR, 0o700))\n }\n\n // Creates a hard link at the path specified by `link` that points to the same file or directory as the path specified by `target`.\n //\n // A hard link is a directory entry that points to the same inode as another directory entry. It allows multiple paths to refer to the same file on the file system.\n //\n // - `link`: The path at which to create the new hard link.\n // - `target`: The path of the existing file or directory to which the hard link should point.\n //\n // Throws an error if `target` path does not exist, or `target` is a directory.\n public func link(\n link: FilePath,\n target: FilePath\n ) throws {\n // ensure that target exists\n guard let targetPtr = self.tree.lookup(path: target) else {\n throw Error.notFound(target)\n }\n let targetNode = targetPtr.pointee\n let targetInodePtr = self.inodes[Int(targetNode.inode) - 1]\n var targetInode = targetInodePtr.pointee\n // ensure that target is not a directory since hardlinks cannot be\n // created to directories\n if targetInode.mode.isDir() {\n throw Error.cannotCreateHardlinksToDirTarget(link)\n }\n targetInode.linksCount += 1\n targetInodePtr.initialize(to: targetInode)\n let parentPath: FilePath = link.dir\n if self.tree.lookup(path: link) != nil {\n try self.unlink(path: link)\n }\n guard let parentTreeNodePtr = self.tree.lookup(path: parentPath) else {\n throw Error.notFound(parentPath)\n }\n let parentTreeNode = parentTreeNodePtr.pointee\n let parentInodePtr = self.inodes[Int(parentTreeNode.inode) - 1]\n let parentInode = parentInodePtr.pointee\n guard parentInode.linksCount < EXT4.MaxLinks else {\n throw Error.maximumLinksExceeded(parentPath)\n }\n let linkTreeNodePtr = Ptr.allocate(capacity: 1)\n let linkTreeNode = FileTree.FileTreeNode(\n inode: InodeNumber(2), // this field is ignored, using 2 so array operations dont panic\n name: link.base,\n parent: parentTreeNodePtr,\n children: [],\n blocks: nil,\n link: targetNode.inode\n )\n linkTreeNodePtr.initialize(to: linkTreeNode)\n parentTreeNode.children.append(linkTreeNodePtr)\n parentTreeNodePtr.initialize(to: parentTreeNode)\n }\n\n // Deletes the file or directory at the specified path from the filesystem.\n //\n // It performs the following actions\n // - set link count of the file's inode to 0\n // - recursively set link count to 0 for its children\n // - free the inode\n // - free data blocks\n // - remove directory entry\n //\n // - `path`: The `FilePath` specifying the path of the file or directory to delete.\n public func unlink(path: FilePath, directoryWhiteout: Bool = false) throws {\n guard let pathPtr = self.tree.lookup(path: path) else {\n // We are being asked to unlink something that does not exist. Ignore\n return\n }\n let pathNode = pathPtr.pointee\n let inodeNumber = Int(pathNode.inode) - 1\n let pathInodePtr = self.inodes[inodeNumber]\n var pathInode = pathInodePtr.pointee\n\n if directoryWhiteout && !pathInode.mode.isDir() {\n throw Error.notDirectory(path)\n }\n\n for childPtr in pathNode.children {\n try self.unlink(path: path.join(childPtr.pointee.name))\n }\n\n guard !directoryWhiteout else {\n return\n }\n\n if let parentNodePtr = self.tree.lookup(path: path.dir) {\n let parentNode = parentNodePtr.pointee\n let parentInodePtr = self.inodes[Int(parentNode.inode) - 1]\n var parentInode = parentInodePtr.pointee\n if pathInode.mode.isDir() {\n if parentInode.linksCount > 2 {\n parentInode.linksCount -= 1\n }\n }\n parentInodePtr.initialize(to: parentInode)\n parentNode.children.removeAll { childPtr in\n childPtr.pointee.name == path.base\n }\n parentNodePtr.initialize(to: parentNode)\n }\n\n if let hardlink = pathNode.link {\n // the file we are deleting is a hardlink, decrement the link count\n let linkedInodePtr = self.inodes[Int(hardlink - 1)]\n var linkedInode = linkedInodePtr.pointee\n if linkedInode.linksCount > 2 {\n linkedInode.linksCount -= 1\n linkedInodePtr.initialize(to: linkedInode)\n }\n }\n\n guard inodeNumber > FirstInode else {\n // Free the inodes and the blocks related to the inode only if its valid\n return\n }\n if let blocks = pathNode.blocks {\n if !(blocks.start == blocks.end) {\n self.deletedBlocks.append((start: blocks.start, end: blocks.end))\n }\n }\n for block in pathNode.additionalBlocks ?? [] {\n self.deletedBlocks.append((start: block.start, end: block.end))\n }\n let now = Date().fs()\n pathInode = Inode()\n pathInode.dtime = now.lo\n pathInodePtr.initialize(to: pathInode)\n }\n\n // Creates a file, directory, or symlink at the specified path, recursively creating parent directories if they don't already exist.\n //\n // - Parameters:\n // - path: The FilePath representing the path where the file, directory, or symlink should be created.\n // - link: An optional FilePath representing the target path for a symlink. If `nil`, a regular file or directory will be created. Preceding '/' should be omitted\n // - mode: The permissions to set for the created file, directory, or symlink.\n // - buf: An `InputStream` object providing the contents for the created file. Ignored when creating directories or symlinks.\n //\n // - Note:\n // - This function recursively creates parent directories if they don't already exist. The `uid` and `gid` of the created parent directories are set to the values of their parent's `uid` and `gid`.\n // - It is expected that the user sets the permissions explicitly later\n // - This function only supports creating files, directories, and symlinks. Attempting to create other types of file system objects will result in an error.\n // - In case of symlinks, the preceding '/' should be omitted\n //\n // - Example usage:\n // ```swift\n // let formatter = EXT4.Formatter(devicePath: \"ext4.img\")\n // // create a directory\n // try formatter.create(path: FilePath(\"/dir\"),\n // mode: EXT4.Inode.Mode(.S_IFDIR, 0o700))\n //\n // // create a file\n // let inputStream = InputStream(data: \"data\".data(using: .utf8)!)\n // inputStream.open()\n // try formatter.create(path: FilePath(\"/dir/file\"),\n // mode: EXT4.Inode.Mode(.S_IFREG, 0o755), buf: inputStream)\n // inputStream.close()\n //\n // // create a symlink\n // try formatter.create(path: FilePath(\"/symlink\"), link: \"/dir/file\",\n // mode: EXT4.Inode.Mode(.S_IFLNK, 0o700))\n // ```\n public func create(\n path: FilePath,\n link: FilePath? = nil, // to create symbolic links\n mode: UInt16,\n ts: FileTimestamps = FileTimestamps(),\n buf: InputStream? = nil,\n uid: UInt32? = nil,\n gid: UInt32? = nil,\n xattrs: [String: Data]? = nil,\n recursion: Bool = false\n ) throws {\n if let nodePtr = self.tree.lookup(path: path) {\n let node = nodePtr.pointee\n let inodePtr = self.inodes[Int(node.inode) - 1]\n let inode = inodePtr.pointee\n // Allowed replace\n // -----------------------------\n //\n // Original Type File Directory Symlink\n // ----------------------------------------------\n // File | ✔ | ✘ | ✔\n // Directory | ✘ | ✔ | ✔\n // Symlink | ✔ | ✘ | ✔\n if mode.isDir() {\n if !inode.mode.isDir() {\n guard inode.mode.isLink() else {\n throw Error.notDirectory(path)\n }\n }\n // mkdir -p\n if path.base == node.name {\n guard !recursion else {\n return\n }\n // create a new tree node to replace this one\n var inode = inode\n inode.mode = mode\n if let uid {\n inode.uid = uid.lo\n inode.uidHigh = uid.hi\n }\n if let gid {\n inode.gid = gid.lo\n inode.gidHigh = gid.hi\n }\n inodePtr.initialize(to: inode)\n return\n }\n } else if let _ = node.link { // ok to overwrite links\n try self.unlink(path: path)\n } else { // file can only be overwritten by another file\n if inode.mode.isDir() {\n guard mode.isLink() else { // unless it is a link, then it can be replaced by a dir\n throw Error.notFile(path)\n }\n }\n try self.unlink(path: path)\n }\n }\n // create all predecessors recursively\n let parentPath: FilePath = path.dir\n try self.create(path: parentPath, mode: Inode.Mode(.S_IFDIR, 0o755), recursion: true)\n guard let parentTreeNodePtr = self.tree.lookup(path: parentPath) else {\n throw Error.notFound(parentPath)\n }\n let parentTreeNode = parentTreeNodePtr.pointee\n let parentInodePtr = self.inodes[Int(parentTreeNode.inode) - 1]\n var parentInode = parentInodePtr.pointee\n guard parentInode.linksCount < EXT4.MaxLinks else {\n throw Error.maximumLinksExceeded(parentPath)\n }\n\n let childInodePtr = Ptr.allocate(capacity: 1)\n var childInode = Inode()\n var startBlock: UInt32 = 0\n var endBlock: UInt32 = 0\n defer { // update metadata\n childInodePtr.initialize(to: childInode)\n parentInodePtr.initialize(to: parentInode)\n self.inodes.append(childInodePtr)\n let childTreeNodePtr = Ptr.allocate(capacity: 1)\n let childTreeNode = FileTree.FileTreeNode(\n inode: InodeNumber(self.inodes.count),\n name: path.base,\n parent: parentTreeNodePtr,\n children: [],\n blocks: (startBlock, endBlock)\n )\n childTreeNodePtr.initialize(to: childTreeNode)\n parentTreeNode.children.append(childTreeNodePtr)\n parentTreeNodePtr.initialize(to: parentTreeNode)\n }\n childInode.mode = mode\n // uid,gid\n if let uid {\n childInode.uid = UInt16(uid & 0xffff)\n childInode.uidHigh = UInt16((uid >> 16) & 0xffff)\n } else {\n childInode.uid = parentInode.uid\n childInode.uidHigh = parentInode.uidHigh\n }\n if let gid {\n childInode.gid = UInt16(gid & 0xffff)\n childInode.gidHigh = UInt16((gid >> 16) & 0xffff)\n } else {\n childInode.gid = parentInode.gid\n childInode.gidHigh = parentInode.gidHigh\n }\n if let xattrs, !xattrs.isEmpty {\n var state = FileXattrsState(\n inode: UInt32(self.inodes.count), inodeXattrCapacity: EXT4.InodeExtraSize, blockCapacity: blockSize)\n try state.add(ExtendedAttribute(name: \"system.data\", value: []))\n for (s, d) in xattrs {\n let attribute = ExtendedAttribute(name: s, value: [UInt8](d))\n try state.add(attribute)\n }\n if !state.inlineAttributes.isEmpty {\n var buffer: [UInt8] = .init(repeating: 0, count: Int(EXT4.InodeExtraSize))\n try state.writeInlineAttributes(buffer: &buffer)\n childInode.inlineXattrs = (\n buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5], buffer[6], buffer[7],\n buffer[8],\n buffer[9],\n buffer[10], buffer[11], buffer[12], buffer[13], buffer[14], buffer[15], buffer[16], buffer[17],\n buffer[18],\n buffer[19],\n buffer[20], buffer[21], buffer[22], buffer[23], buffer[24], buffer[25], buffer[26], buffer[27],\n buffer[28],\n buffer[29],\n buffer[30], buffer[31], buffer[32], buffer[33], buffer[34], buffer[35], buffer[36], buffer[37],\n buffer[38],\n buffer[39],\n buffer[40], buffer[41], buffer[42], buffer[43], buffer[44], buffer[45], buffer[46], buffer[47],\n buffer[48],\n buffer[49],\n buffer[50], buffer[51], buffer[52], buffer[53], buffer[54], buffer[55], buffer[56], buffer[57],\n buffer[58],\n buffer[59],\n buffer[60], buffer[61], buffer[62], buffer[63], buffer[64], buffer[65], buffer[66], buffer[67],\n buffer[68],\n buffer[69],\n buffer[70], buffer[71], buffer[72], buffer[73], buffer[74], buffer[75], buffer[76], buffer[77],\n buffer[78],\n buffer[79],\n buffer[80], buffer[81], buffer[82], buffer[83], buffer[84], buffer[85], buffer[86], buffer[87],\n buffer[88],\n buffer[89],\n buffer[90], buffer[91], buffer[92], buffer[93], buffer[94], buffer[95]\n )\n childInode.flags |= InodeFlag.inlineData.rawValue\n }\n if !state.blockAttributes.isEmpty {\n var buffer: [UInt8] = .init(repeating: 0, count: Int(blockSize))\n try state.writeBlockAttributes(buffer: &buffer)\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n childInode.xattrBlockLow = self.currentBlock\n try self.handle.write(contentsOf: buffer)\n childInode.blocksLow += 1\n }\n }\n\n childInode.atime = ts.accessLo\n childInode.atimeExtra = ts.accessHi\n // ctime is the last time the inode was changed which is now\n childInode.ctime = ts.nowLo\n childInode.ctimeExtra = ts.nowHi\n childInode.mtime = ts.modificationLo\n childInode.mtimeExtra = ts.modificationHi\n childInode.crtime = ts.creationLo\n childInode.crtimeExtra = ts.creationHi\n childInode.linksCount = 1\n childInode.extraIsize = UInt16(EXT4.ExtraIsize)\n // flags\n childInode.flags = InodeFlag.hugeFile.rawValue\n // size check\n var size: UInt64 = 0\n // align with block boundary\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n // dir\n if childInode.mode.isDir() {\n childInode.linksCount += 1\n parentInode.linksCount += 1\n // to pass e2fsck, the convention is to sort children\n // before committing to disk. Therefore, we are deferring\n // writing dentries until commit() is called\n return\n }\n // symbolic link\n if let link {\n startBlock = self.currentBlock\n let linkPath = link.bytes\n if linkPath.count < 60 {\n size += UInt64(linkPath.count)\n var blockData: [UInt8] = .init(repeating: 0, count: 60)\n for i in 0...allocate(capacity: Int(self.blockSize))\n defer { tempBuf.deallocate() }\n while case let block = buf.read(tempBuf.underlying, maxLength: Int(self.blockSize)), block > 0 {\n size += UInt64(block)\n if size > EXT4.MaxFileSize {\n throw Error.fileTooBig(size)\n }\n let data = UnsafeRawBufferPointer(start: tempBuf.underlying, count: block)\n try withUnsafeLittleEndianBuffer(of: data) { b in\n try self.handle.write(contentsOf: b)\n }\n }\n }\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n endBlock = self.currentBlock\n childInode.sizeLow = size.lo\n childInode.sizeHigh = size.hi\n childInode = try self.writeExtents(childInode, (startBlock, endBlock))\n return\n }\n // FIFO, Socket and other types are not handled\n throw Error.unsupportedFiletype\n }\n\n public func setOwner(path: FilePath, uid: UInt16? = nil, gid: UInt16? = nil, recursive: Bool = false) throws {\n // ensure that target exists\n guard let pathPtr = self.tree.lookup(path: path) else {\n throw Error.notFound(path)\n }\n let pathNode = pathPtr.pointee\n let pathInodePtr = self.inodes[Int(pathNode.inode) - 1]\n var pathInode = pathInodePtr.pointee\n if let uid {\n pathInode.uid = uid\n }\n if let gid {\n pathInode.gid = gid\n }\n pathInodePtr.initialize(to: pathInode)\n if recursive {\n for childPtr in pathNode.children {\n let child = childPtr.pointee\n try self.setOwner(path: path.join(child.name), uid: uid, gid: gid, recursive: recursive)\n }\n }\n }\n\n // Completes the formatting of an ext4 filesystem after writing the necessary structures.\n //\n // This function is responsible for finalizing the formatting process of an ext4 filesystem\n // after the following structures have been written:\n // - Inode table: Contains information about each file and directory in the filesystem.\n // - Block bitmap: Tracks the allocation status of each block in the filesystem.\n // - Inode bitmap: Tracks the allocation status of each inode in the filesystem.\n // - Directory tree: Represents the hierarchical structure of directories and files.\n // - Group descriptors: Stores metadata about each block group in the filesystem.\n // - Superblock: Contains essential information about the filesystem's configuration.\n //\n // The function performs any necessary final steps to ensure the integrity and consistency\n // of the ext4 filesystem before it can be mounted and used.\n public func close() throws {\n var breathWiseChildTree: [(parent: Ptr?, child: Ptr)] = [\n (nil, self.tree.root)\n ]\n while !breathWiseChildTree.isEmpty {\n let (parent, child) = breathWiseChildTree.removeFirst()\n try self.commit(parent, child) // commit directories iteratively\n if child.pointee.link != nil {\n continue\n }\n breathWiseChildTree.append(contentsOf: child.pointee.children.map { (child, $0) })\n }\n let blockGroupSize = optimizeBlockGroupLayout(blocks: self.currentBlock, inodes: UInt32(self.inodes.count))\n let inodeTableOffset = try self.commitInodeTable(\n blockGroups: blockGroupSize.blockGroups,\n inodesPerGroup: blockGroupSize.inodesPerGroup\n )\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n // write bitmaps and group descriptors\n\n let bitmapOffset = self.currentBlock\n let bitmapSize: UInt32 = blockGroupSize.blockGroups * 2 // each group has two bitmaps - for inodes, and for blocks\n let dataSize: UInt32 = bitmapOffset + bitmapSize // last data block\n var diskSize = dataSize\n var minimumDiskSize = (blockGroupSize.blockGroups - 1) * self.blocksPerGroup + 1\n if blockGroupSize.blockGroups == 1 {\n minimumDiskSize = self.blocksPerGroup // at least 1 block group\n }\n if diskSize < minimumDiskSize { // for data + metadata\n diskSize = minimumDiskSize\n }\n if self.size < minimumDiskSize {\n self.size = UInt64(minimumDiskSize) * self.blockSize\n }\n // number of blocks needed for group descriptors\n let groupDescriptorBlockCount: UInt32 = (blockGroupSize.blockGroups - 1) / self.groupsPerDescriptorBlock + 1\n guard groupDescriptorBlockCount <= self.groupDescriptorBlocks else {\n throw Error.insufficientSpaceForGroupDescriptorBlocks\n }\n\n var totalBlocks: UInt32 = 0\n var totalInodes: UInt32 = 0\n let inodeTableSizePerGroup: UInt32 = blockGroupSize.inodesPerGroup * EXT4.InodeSize / self.blockSize\n var groupDescriptors: [GroupDescriptor] = []\n\n let minGroups = (((self.pos / UInt64(self.blockSize)) - 1) / UInt64(self.blocksPerGroup)) + 1\n if self.size < minGroups * blocksPerGroup * blockSize {\n self.size = UInt64(minGroups * blocksPerGroup * blockSize)\n let pos = self.pos\n guard lseek(self.handle.fileDescriptor, off_t(self.size - 1), 0) == self.size - 1 else {\n throw Error.cannotResizeFS(self.size)\n }\n let zero: [UInt8] = [0]\n try self.handle.write(contentsOf: zero)\n try self.handle.seek(toOffset: pos)\n }\n let totalGroups = (((self.size / UInt64(self.blockSize)) - 1) / UInt64(self.blocksPerGroup)) + 1\n\n // If the provided disk size is not aligned to a blockgroup boundary, it needs to\n // be expanded to the next blockgroup boundary.\n // Example:\n // Provided disk size: 2 GB + 100MB: 2148 MB\n // BlockSize: 4096\n // Blockgroup size: 32768 blocks: 128MB\n // Number of blocks: 549888\n // Number of blockgroups = 549888 / 32768 = 16.78125\n // Aligned disk size = 557056 blocks = 17 blockgroups: 2176 MB\n if self.size < totalGroups * blocksPerGroup * blockSize {\n self.size = UInt64(totalGroups * blocksPerGroup * blockSize)\n let pos = self.pos\n guard lseek(self.handle.fileDescriptor, off_t(self.size - 1), 0) == self.size - 1 else {\n throw Error.cannotResizeFS(self.size)\n }\n let zero: [UInt8] = [0]\n try self.handle.write(contentsOf: zero)\n try self.handle.seek(toOffset: pos)\n }\n for group in 0..> (j % 8)) & 1)\n bitmap[Int(j / 8)] &= ~(1 << (j % 8))\n }\n }\n\n // inodes bitmap goes into second bitmap block\n for i in 0.. self.inodes.count {\n continue\n }\n let inode = self.inodes[Int(ino) - 1]\n if ino > 10 && inode.pointee.linksCount == 0 { // deleted files\n continue\n }\n bitmap[Int(self.blockSize) + Int(i / 8)] |= 1 << (i % 8)\n inodes += 1\n if inode.pointee.mode.isDir() {\n dirs += 1\n }\n }\n\n for i in (blockGroupSize.inodesPerGroup / 8)...init(repeating: 0, count: 1024))\n\n let computedInodes = totalGroups * blockGroupSize.inodesPerGroup\n var blocksCount = totalGroups * self.blocksPerGroup\n while blocksCount < totalBlocks {\n blocksCount = UInt64(totalBlocks)\n }\n let totalFreeBlocks: UInt64\n if totalBlocks > blocksCount {\n totalFreeBlocks = 0\n } else {\n totalFreeBlocks = blocksCount - totalBlocks\n }\n var superblock = SuperBlock()\n superblock.inodesCount = computedInodes.lo\n superblock.blocksCountLow = blocksCount.lo\n superblock.blocksCountHigh = blocksCount.hi\n superblock.freeBlocksCountLow = totalFreeBlocks.lo\n superblock.freeBlocksCountHigh = totalFreeBlocks.hi\n let freeInodesCount = computedInodes.lo - totalInodes\n superblock.freeInodesCount = freeInodesCount\n superblock.firstDataBlock = 0\n superblock.logBlockSize = 2\n superblock.logClusterSize = 2\n superblock.blocksPerGroup = self.blocksPerGroup\n superblock.clustersPerGroup = self.blocksPerGroup\n superblock.inodesPerGroup = blockGroupSize.inodesPerGroup\n superblock.magic = EXT4.SuperBlockMagic\n superblock.state = 1 // cleanly unmounted\n superblock.errors = 1 // continue on error\n superblock.creatorOS = 3 // freeBSD\n superblock.revisionLevel = 1 // dynamic inode sizes\n superblock.firstInode = EXT4.FirstInode\n superblock.lpfInode = EXT4.LostAndFoundInode\n superblock.inodeSize = UInt16(EXT4.InodeSize)\n superblock.featureCompat = CompatFeature.sparseSuper2 | CompatFeature.extAttr\n superblock.featureIncompat =\n IncompatFeature.filetype | IncompatFeature.extents | IncompatFeature.flexBg | IncompatFeature.inlineData\n superblock.featureRoCompat =\n RoCompatFeature.largeFile | RoCompatFeature.hugeFile | RoCompatFeature.extraIsize\n superblock.minExtraIsize = EXT4.ExtraIsize\n superblock.wantExtraIsize = EXT4.ExtraIsize\n superblock.logGroupsPerFlex = 31\n superblock.uuid = UUID().uuid\n try withUnsafeLittleEndianBytes(of: superblock) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n try self.handle.write(contentsOf: Array.init(repeating: 0, count: 2048))\n }\n\n // MARK: Private Methods and Properties\n private var handle: FileHandle\n private var inodes: [Ptr]\n private var tree: FileTree\n private var deletedBlocks: [(start: UInt32, end: UInt32)] = []\n\n private var pos: UInt64 {\n guard let offset = try? self.handle.offset() else {\n return 0\n }\n return offset\n }\n\n private var currentBlock: UInt32 {\n self.pos / self.blockSize\n }\n\n private func seek(block: UInt32) throws {\n try self.handle.seek(toOffset: UInt64(block) * blockSize)\n }\n\n private func commitInodeTable(blockGroups: UInt32, inodesPerGroup: UInt32) throws -> UInt64 {\n // inodeTable must go into a new block\n if self.pos % blockSize != 0 {\n try seek(block: currentBlock + 1)\n }\n let inodeTableOffset = UInt64(currentBlock)\n\n let inodeSize = MemoryLayout.size\n // Write InodeTable\n for inode in self.inodes {\n try withUnsafeLittleEndianBytes(of: inode.pointee) { bytes in\n try handle.write(contentsOf: bytes)\n }\n try self.handle.write(\n contentsOf: Array.init(repeating: 0, count: Int(EXT4.InodeSize) - inodeSize))\n }\n let tableSize: UInt64 = UInt64(EXT4.InodeSize) * blockGroups * inodesPerGroup\n let rest = tableSize - uint32(self.inodes.count) * EXT4.InodeSize\n let zeroBlock = Array.init(repeating: 0, count: Int(self.blockSize))\n for _ in 0..<(rest / self.blockSize) {\n try self.handle.write(contentsOf: zeroBlock)\n }\n try self.handle.write(contentsOf: Array.init(repeating: 0, count: Int(rest % self.blockSize)))\n return inodeTableOffset\n }\n\n // optimizes the distribution of blockGroups to obtain the lowest number of blockGroups needed to\n // represent all the inodes and all the blocks in the FS\n private func optimizeBlockGroupLayout(blocks: UInt32, inodes: UInt32) -> (\n blockGroups: UInt32, inodesPerGroup: UInt32\n ) {\n // counts the number of blockGroups given a particular inodesPerGroup size\n let groupCount: (_ blocks: UInt32, _ inodes: UInt32, _ inodesPerGroup: UInt32) -> UInt32 = {\n blocks, inodes, inodesPerGroup in\n let inodeBlocksPerGroup: UInt32 = inodesPerGroup * EXT4.InodeSize / self.blockSize\n let dataBlocksPerGroup: UInt32 = self.blocksPerGroup - inodeBlocksPerGroup - 2 // save room for the bitmaps\n // Increase the block count to ensure there are enough groups for all the inodes.\n let minBlocks: UInt32 = (inodes - 1) / inodesPerGroup * dataBlocksPerGroup + 1\n var updatedBlocks = blocks\n if blocks < minBlocks {\n updatedBlocks = minBlocks\n }\n return (updatedBlocks + dataBlocksPerGroup - 1) / dataBlocksPerGroup\n }\n\n var groups: UInt32 = UInt32.max\n var inodesPerGroup: UInt32 = 0\n let inc = Int(self.blockSize * 512) / Int(EXT4.InodeSize) // inodesPerGroup\n // minimizes the number of blockGroups needed to its lowest value\n for ipg in stride(from: inc, through: Int(self.maxInodesPerGroup), by: inc) {\n let g = groupCount(blocks, inodes, UInt32(ipg))\n if g < groups {\n groups = g\n inodesPerGroup = UInt32(ipg)\n }\n }\n return (groups, inodesPerGroup)\n }\n\n private func commit(_ parentPtr: Ptr?, _ nodePtr: Ptr) throws {\n let node = nodePtr.pointee\n let inodePtr = self.inodes[Int(node.inode) - 1]\n var inode = inodePtr.pointee\n guard inode.linksCount > 0 else {\n return\n }\n if node.link != nil {\n return\n }\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n if inode.mode.isDir() {\n let startBlock = self.currentBlock\n var left: Int = Int(self.blockSize)\n try writeDirEntry(name: \".\", inode: node.inode, left: &left)\n if let parent = parentPtr {\n try writeDirEntry(name: \"..\", inode: parent.pointee.inode, left: &left)\n } else {\n try writeDirEntry(name: \"..\", inode: node.inode, left: &left)\n }\n var sortedChildren = Array(node.children)\n sortedChildren.sort { left, right in\n left.pointee.inode < right.pointee.inode\n }\n for childPtr in sortedChildren {\n let child = childPtr.pointee\n try writeDirEntry(name: child.name, inode: child.inode, left: &left, link: child.link)\n }\n try finishDirEntryBlock(&left)\n let endBlock = self.currentBlock\n let size: UInt64 = UInt64(endBlock - startBlock) * self.blockSize\n inode.sizeLow = size.lo\n inode.sizeHigh = size.hi\n inodePtr.initialize(to: inode)\n node.blocks = (startBlock, endBlock)\n nodePtr.initialize(to: node)\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n inode = try self.writeExtents(inode, (startBlock, endBlock))\n inodePtr.initialize(to: inode)\n }\n }\n\n private func fillExtents(\n node: inout ExtentLeafNode, numExtents: UInt32, numBlocks: UInt32, start: UInt32, offset: UInt32\n ) {\n for i in 0.. EXT4.MaxBlocksPerExtent {\n length = EXT4.MaxBlocksPerExtent\n }\n let extentStart: UInt32 = start + extentBlock\n let extent = ExtentLeaf(\n block: extentBlock,\n length: UInt16(length),\n startHigh: 0,\n startLow: extentStart\n )\n node.leaves.append(extent)\n }\n }\n\n private func writeExtents(_ inode: Inode, _ blocks: (start: UInt32, end: UInt32)) throws -> Inode {\n var inode = inode\n // rest of code assumes that extents MUST go into a new block\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n let dataBlocks = blocks.end - blocks.start\n let numExtents = (dataBlocks + EXT4.MaxBlocksPerExtent - 1) / EXT4.MaxBlocksPerExtent\n var usedBlocks = dataBlocks\n let extentNodeSize = 12\n let extentsPerBlock = self.blockSize / extentNodeSize - 1\n var blockData: [UInt8] = .init(repeating: 0, count: 60)\n var blockIndex: Int = 0\n switch numExtents {\n case 0:\n return inode // noop\n case 1..<5:\n let extentHeader = ExtentHeader(\n magic: EXT4.ExtentHeaderMagic,\n entries: UInt16(numExtents),\n max: 4,\n depth: 0,\n generation: 0)\n\n var node = ExtentLeafNode(header: extentHeader, leaves: [])\n fillExtents(node: &node, numExtents: numExtents, numBlocks: dataBlocks, start: blocks.start, offset: 0)\n withUnsafeLittleEndianBytes(of: node.header) { bytes in\n for b in bytes {\n blockData[blockIndex] = b\n blockIndex = blockIndex + 1\n }\n }\n for leaf in node.leaves {\n withUnsafeLittleEndianBytes(of: leaf) { bytes in\n for b in bytes {\n blockData[blockIndex] = b\n blockIndex = blockIndex + 1\n }\n }\n }\n case 5..<4 * UInt32(extentsPerBlock) + 1:\n let extentBlocks = numExtents / extentsPerBlock + 1\n usedBlocks += extentBlocks\n let extentHeader = ExtentHeader(\n magic: EXT4.ExtentHeaderMagic,\n entries: UInt16(extentBlocks),\n max: 4,\n depth: 1,\n generation: 0\n )\n var root = ExtentIndexNode(header: extentHeader, indices: [])\n for i in 0.. extentsPerBlock {\n extentsInBlock = extentsPerBlock\n }\n let leafHeader = ExtentHeader(\n magic: EXT4.ExtentHeaderMagic,\n entries: UInt16(extentsInBlock),\n max: UInt16(extentsPerBlock),\n depth: 0,\n generation: 0\n )\n var leafNode = ExtentLeafNode(header: leafHeader, leaves: [])\n let offset = i * extentsPerBlock * EXT4.MaxBlocksPerExtent\n fillExtents(\n node: &leafNode, numExtents: extentsInBlock, numBlocks: dataBlocks,\n start: blocks.start + offset,\n offset: offset)\n try withUnsafeLittleEndianBytes(of: leafNode.header) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n for leaf in leafNode.leaves {\n try withUnsafeLittleEndianBytes(of: leaf) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n }\n let extentTail = ExtentTail(checksum: leafNode.leaves.last!.block)\n try withUnsafeLittleEndianBytes(of: extentTail) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n root.indices.append(extentIdx)\n }\n withUnsafeLittleEndianBytes(of: root.header) { bytes in\n for b in bytes {\n blockData[blockIndex] = b\n blockIndex = blockIndex + 1\n }\n }\n for leaf in root.indices {\n withUnsafeLittleEndianBytes(of: leaf) { bytes in\n for b in bytes {\n blockData[blockIndex] = b\n blockIndex = blockIndex + 1\n }\n }\n }\n default:\n throw Error.fileTooBig(UInt64(dataBlocks) * self.blockSize)\n }\n inode.block = (\n blockData[0], blockData[1], blockData[2], blockData[3], blockData[4], blockData[5], blockData[6],\n blockData[7],\n blockData[8], blockData[9],\n blockData[10], blockData[11], blockData[12], blockData[13], blockData[14], blockData[15], blockData[16],\n blockData[17], blockData[18], blockData[19],\n blockData[20], blockData[21], blockData[22], blockData[23], blockData[24], blockData[25], blockData[26],\n blockData[27], blockData[28], blockData[29],\n blockData[30], blockData[31], blockData[32], blockData[33], blockData[34], blockData[35], blockData[36],\n blockData[37], blockData[38], blockData[39],\n blockData[40], blockData[41], blockData[42], blockData[43], blockData[44], blockData[45], blockData[46],\n blockData[47], blockData[48], blockData[49],\n blockData[50], blockData[51], blockData[52], blockData[53], blockData[54], blockData[55], blockData[56],\n blockData[57], blockData[58], blockData[59]\n )\n // ensure that inode's block count includes extent blocks\n inode.blocksLow += usedBlocks\n inode.flags = InodeFlag.extents | inode.flags\n return inode\n }\n // writes a single directory entry\n private func writeDirEntry(name: String, inode: InodeNumber, left: inout Int, link: InodeNumber? = nil) throws {\n guard self.inodes[Int(inode) - 1].pointee.linksCount > 0 else {\n return\n }\n guard let nameData = name.data(using: .utf8) else {\n throw Error.invalidName(name)\n }\n let directoryEntrySize = MemoryLayout.size\n let rlb = directoryEntrySize + nameData.count\n let rl = (rlb + 3) & ~3\n if left < rl + 12 {\n try self.finishDirEntryBlock(&left)\n }\n var mode = self.inodes[Int(inode) - 1].pointee.mode\n var inodeNum = inode\n if let link {\n mode = self.inodes[Int(link) - 1].pointee.mode | 0o777\n inodeNum = link\n }\n let entry = DirectoryEntry(\n inode: inodeNum,\n recordLength: UInt16(rl),\n nameLength: UInt8(nameData.count),\n fileType: mode.fileType()\n )\n try withUnsafeLittleEndianBytes(of: entry) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n\n try nameData.withUnsafeBytes { buffer in\n try withUnsafeLittleEndianBuffer(of: buffer) { b in\n try self.handle.write(contentsOf: b)\n }\n }\n try self.handle.write(contentsOf: [UInt8](repeating: 0, count: rl - rlb))\n left = left - rl\n }\n\n private func finishDirEntryBlock(_ left: inout Int) throws {\n defer { left = Int(self.blockSize) }\n if left <= 0 {\n return\n }\n let entry = DirectoryEntry(\n inode: InodeNumber(0),\n recordLength: UInt16(left),\n nameLength: 0,\n fileType: 0\n )\n try withUnsafeLittleEndianBytes(of: entry) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n left = left - MemoryLayout.size\n if left < 4 {\n throw Error.noSpaceForTrailingDEntry\n }\n try self.handle.write(contentsOf: [UInt8](repeating: 0, count: Int(left)))\n }\n\n public enum Error: Swift.Error, CustomStringConvertible, Sendable, Equatable {\n case notDirectory(_ path: FilePath)\n case notFile(_ path: FilePath)\n case notFound(_ path: FilePath)\n case alreadyExists(_ path: FilePath)\n case unsupportedFiletype\n case maximumLinksExceeded(_ path: FilePath)\n case fileTooBig(_ size: UInt64)\n case invalidLink(_ path: FilePath)\n case invalidName(_ name: String)\n case noSpaceForTrailingDEntry\n case insufficientSpaceForGroupDescriptorBlocks\n case cannotCreateHardlinksToDirTarget(_ path: FilePath)\n case cannotTruncateFile(_ path: FilePath)\n case cannotCreateSparseFile(_ path: FilePath)\n case cannotResizeFS(_ size: UInt64)\n public var description: String {\n switch self {\n case .notDirectory(let path):\n return \"\\(path) is not a directory\"\n case .notFile(let path):\n return \"\\(path) is not a file\"\n case .notFound(let path):\n return \"\\(path) not found\"\n case .alreadyExists(let path):\n return \"\\(path) already exists\"\n case .unsupportedFiletype:\n return \"file type not supported\"\n case .maximumLinksExceeded(let path):\n return \"maximum links exceeded for path: \\(path)\"\n case .fileTooBig(let size):\n return \"\\(size) exceeds max file size (128 GiB)\"\n case .invalidLink(let path):\n return \"'\\(path)' is an invalid link\"\n case .invalidName(let name):\n return \"'\\(name)' is an invalid name\"\n case .noSpaceForTrailingDEntry:\n return \"not enough space for trailing dentry\"\n case .insufficientSpaceForGroupDescriptorBlocks:\n return \"not enough space for group descriptor blocks\"\n case .cannotCreateHardlinksToDirTarget(let path):\n return \"cannot create hard links to directory target: \\(path)\"\n case .cannotTruncateFile(let path):\n return \"cannot truncate file: \\(path)\"\n case .cannotCreateSparseFile(let path):\n return \"cannot create sparse file at \\(path)\"\n case .cannotResizeFS(let size):\n return \"cannot resize fs to \\(size) bytes\"\n }\n }\n }\n\n deinit {\n for inode in inodes {\n inode.deinitialize(count: 1)\n inode.deallocate()\n }\n self.inodes.removeAll()\n }\n }\n}\n\nextension Date {\n func fs() -> UInt64 {\n if self == Date.distantPast {\n return 0\n }\n\n let s = self.timeIntervalSince1970\n\n if s < -0x8000_0000 {\n return 0x8000_0000\n }\n\n if s > 0x3_7fff_ffff {\n return 0x3_7fff_ffff\n }\n\n let seconds = UInt64(s)\n let nanoseconds = UInt64(self.timeIntervalSince1970.truncatingRemainder(dividingBy: 1) * 1_000_000_000)\n\n return seconds | (nanoseconds << 34)\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/RegistryClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport NIO\nimport NIOHTTP1\n\n#if os(macOS)\nimport Network\n#endif\n\n/// Data used to control retry behavior for `RegistryClient`.\npublic struct RetryOptions: Sendable {\n /// The maximum number of retries to attempt before failing.\n public var maxRetries: Int\n /// The retry interval in nanoseconds.\n public var retryInterval: UInt64\n /// A provided closure to handle if a given HTTP response should be\n /// retried.\n public var shouldRetry: (@Sendable (HTTPClientResponse) -> Bool)?\n\n public init(maxRetries: Int, retryInterval: UInt64, shouldRetry: (@Sendable (HTTPClientResponse) -> Bool)? = nil) {\n self.maxRetries = maxRetries\n self.retryInterval = retryInterval\n self.shouldRetry = shouldRetry\n }\n}\n\n/// A client for interacting with OCI compliant container registries.\npublic final class RegistryClient: ContentClient {\n private static let defaultRetryOptions = RetryOptions(\n maxRetries: 3,\n retryInterval: 1_000_000_000,\n shouldRetry: ({ response in\n response.status.code >= 500\n })\n )\n\n let client: HTTPClient\n let base: URLComponents\n let clientID: String\n let authentication: Authentication?\n let retryOptions: RetryOptions?\n let bufferSize: Int\n\n public convenience init(\n reference: String,\n insecure: Bool = false,\n auth: Authentication? = nil,\n logger: Logger? = nil\n ) throws {\n let ref = try Reference.parse(reference)\n guard let domain = ref.resolvedDomain else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid domain for image reference \\(reference)\")\n }\n let scheme = insecure ? \"http\" : \"https\"\n let _url = \"\\(scheme)://\\(domain)\"\n guard let url = URL(string: _url) else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot convert \\(_url) to URL\")\n }\n guard let host = url.host else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid host \\(domain)\")\n }\n let port = url.port\n self.init(\n host: host,\n scheme: scheme,\n port: port,\n authentication: auth,\n retryOptions: Self.defaultRetryOptions\n )\n }\n\n public init(\n host: String,\n scheme: String? = \"https\",\n port: Int? = nil,\n authentication: Authentication? = nil,\n clientID: String? = nil,\n retryOptions: RetryOptions? = nil,\n bufferSize: Int = Int(4.mib()),\n logger: Logger? = nil\n ) {\n var components = URLComponents()\n components.scheme = scheme\n components.host = host\n components.port = port\n\n self.base = components\n self.clientID = clientID ?? \"containerization-registry-client\"\n self.authentication = authentication\n self.retryOptions = retryOptions\n self.bufferSize = bufferSize\n var httpConfiguration = HTTPClient.Configuration()\n let proxyConfig: HTTPClient.Configuration.Proxy? = {\n let proxyEnv = ProcessInfo.processInfo.environment[\"HTTP_PROXY\"]\n guard let proxyEnv else {\n return nil\n }\n guard let url = URL(string: proxyEnv), let host = url.host(), let port = url.port else {\n return nil\n }\n return .server(host: host, port: port)\n }()\n httpConfiguration.proxy = proxyConfig\n if let logger {\n self.client = HTTPClient(eventLoopGroupProvider: .singleton, configuration: httpConfiguration, backgroundActivityLogger: logger)\n } else {\n self.client = HTTPClient(eventLoopGroupProvider: .singleton, configuration: httpConfiguration)\n }\n }\n\n deinit {\n _ = client.shutdown()\n }\n\n func host() -> String {\n base.host ?? \"\"\n }\n\n internal func request(\n components: URLComponents,\n method: HTTPMethod = .GET,\n bodyClosure: () throws -> HTTPClientRequest.Body? = { nil },\n headers: [(String, String)]? = nil,\n closure: (HTTPClientResponse) async throws -> T\n ) async throws -> T {\n guard let path = components.url?.absoluteString else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid url \\(components.path)\")\n }\n\n var request = HTTPClientRequest(url: path)\n request.method = method\n\n var currentToken: TokenResponse?\n let token: String? = try await {\n if let basicAuth = authentication {\n return try await basicAuth.token()\n }\n return nil\n }()\n\n if let token {\n request.headers.add(name: \"Authorization\", value: \"\\(token)\")\n }\n\n // Add any arbitrary headers\n headers?.forEach { (k, v) in request.headers.add(name: k, value: v) }\n var retryCount = 0\n var response: HTTPClientResponse?\n while true {\n request.body = try bodyClosure()\n do {\n let _response = try await client.execute(request, deadline: .distantFuture)\n response = _response\n if _response.status == .unauthorized || _response.status == .forbidden {\n let authHeader = _response.headers[TokenRequest.authenticateHeaderName]\n let tokenRequest: TokenRequest\n do {\n tokenRequest = try self.createTokenRequest(parsing: authHeader)\n } catch {\n // The server did not tell us how to authenticate our requests,\n // Or we do not support scheme the server is requesting for.\n // Throw the 401/403 to the caller, and let them decide how to proceed.\n throw RegistryClient.Error.invalidStatus(url: path, _response.status, reason: String(describing: error))\n }\n if let ct = currentToken, ct.isValid(scope: tokenRequest.scope) {\n break\n }\n\n do {\n let _currentToken = try await fetchToken(request: tokenRequest)\n guard let token = _currentToken.getToken() else {\n throw ContainerizationError(.internalError, message: \"Failed to fetch Bearer token\")\n }\n currentToken = _currentToken\n request.headers.replaceOrAdd(name: \"Authorization\", value: token)\n retryCount += 1\n } catch let err as RegistryClient.Error {\n guard case .invalidStatus(_, let status, _) = err else {\n throw err\n }\n if status == .unauthorized || status == .forbidden {\n throw RegistryClient.Error.invalidStatus(url: path, _response.status, reason: \"Access denied or wrong credentials\")\n }\n\n throw err\n }\n\n continue\n }\n guard let retryOptions = self.retryOptions else {\n break\n }\n guard retryCount < retryOptions.maxRetries else {\n break\n }\n guard let shouldRetry = retryOptions.shouldRetry, shouldRetry(_response) else {\n break\n }\n retryCount += 1\n try await Task.sleep(nanoseconds: retryOptions.retryInterval)\n continue\n } catch let err as RegistryClient.Error {\n throw err\n } catch {\n #if os(macOS)\n if let err = error as? NWError {\n if err.errorCode == kDNSServiceErr_NoSuchRecord {\n throw ContainerizationError(.internalError, message: \"No Such DNS Record \\(host())\")\n }\n }\n #endif\n guard let retryOptions = self.retryOptions, retryCount < retryOptions.maxRetries else {\n throw error\n }\n retryCount += 1\n try await Task.sleep(nanoseconds: retryOptions.retryInterval)\n }\n }\n guard let response else {\n throw ContainerizationError(.internalError, message: \"Invalid response\")\n }\n return try await closure(response)\n }\n\n internal func requestData(\n components: URLComponents,\n headers: [(String, String)]? = nil\n ) async throws -> Data {\n let bytes: ByteBuffer = try await requestBuffer(components: components, headers: headers)\n return Data(buffer: bytes)\n }\n\n internal func requestBuffer(\n components: URLComponents,\n headers: [(String, String)]? = nil\n ) async throws -> ByteBuffer {\n try await request(components: components, method: .GET, headers: headers) { response in\n guard response.status == .ok else {\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n\n return try await response.body.collect(upTo: self.bufferSize)\n }\n }\n\n internal func requestJSON(\n components: URLComponents,\n headers: [(String, String)]? = nil\n ) async throws -> T {\n let buffer = try await self.requestBuffer(components: components, headers: headers)\n return try JSONDecoder().decode(T.self, from: buffer)\n }\n\n /// A minimal endpoint, mounted at /v2/ will provide version support information based on its response statuses.\n /// See https://distribution.github.io/distribution/spec/api/#api-version-check\n public func ping() async throws {\n var components = base\n components.path = \"/v2/\"\n\n try await request(components: components) { response in\n guard response.status == .ok else {\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n }\n }\n}\n"], ["/containerization/Sources/Containerization/Mount.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport Virtualization\nimport ContainerizationError\n#endif\n\n/// A filesystem mount exposed to a container.\npublic struct Mount: Sendable {\n /// The filesystem or mount type. This is the string\n /// that will be used for the mount syscall itself.\n public var type: String\n /// The source path of the mount.\n public var source: String\n /// The destination path of the mount.\n public var destination: String\n /// Filesystem or mount specific options.\n public var options: [String]\n /// Runtime specific options. This can be used\n /// as a way to discern what kind of device a vmm\n /// should create for this specific mount (virtioblock\n /// virtiofs etc.).\n public let runtimeOptions: RuntimeOptions\n\n /// A type representing a \"hint\" of what type\n /// of mount this really is (block, directory, purely\n /// guest mount) and a set of type specific options, if any.\n public enum RuntimeOptions: Sendable {\n case virtioblk([String])\n case virtiofs([String])\n case any\n }\n\n init(\n type: String,\n source: String,\n destination: String,\n options: [String],\n runtimeOptions: RuntimeOptions\n ) {\n self.type = type\n self.source = source\n self.destination = destination\n self.options = options\n self.runtimeOptions = runtimeOptions\n }\n\n /// Mount representing a virtio block device.\n public static func block(\n format: String,\n source: String,\n destination: String,\n options: [String] = [],\n runtimeOptions: [String] = []\n ) -> Self {\n .init(\n type: format,\n source: source,\n destination: destination,\n options: options,\n runtimeOptions: .virtioblk(runtimeOptions)\n )\n }\n\n /// Mount representing a virtiofs share.\n public static func share(\n source: String,\n destination: String,\n options: [String] = [],\n runtimeOptions: [String] = []\n ) -> Self {\n .init(\n type: \"virtiofs\",\n source: source,\n destination: destination,\n options: options,\n runtimeOptions: .virtiofs(runtimeOptions)\n )\n }\n\n /// A generic mount.\n public static func any(\n type: String,\n source: String,\n destination: String,\n options: [String] = []\n ) -> Self {\n .init(\n type: type,\n source: source,\n destination: destination,\n options: options,\n runtimeOptions: .any\n )\n }\n\n #if os(macOS)\n /// Clone the Mount to the provided path.\n ///\n /// This uses `clonefile` to provide a copy-on-write copy of the Mount.\n public func clone(to: String) throws -> Self {\n let fm = FileManager.default\n let src = self.source\n try fm.copyItem(atPath: src, toPath: to)\n\n return .init(\n type: self.type,\n source: to,\n destination: self.destination,\n options: self.options,\n runtimeOptions: self.runtimeOptions\n )\n }\n #endif\n}\n\n#if os(macOS)\n\nextension Mount {\n func configure(config: inout VZVirtualMachineConfiguration) throws {\n switch self.runtimeOptions {\n case .virtioblk(let options):\n let device = try VZDiskImageStorageDeviceAttachment.mountToVZAttachment(mount: self, options: options)\n let attachment = VZVirtioBlockDeviceConfiguration(attachment: device)\n config.storageDevices.append(attachment)\n case .virtiofs(_):\n guard FileManager.default.fileExists(atPath: self.source) else {\n throw ContainerizationError(.notFound, message: \"directory \\(source) does not exist\")\n }\n\n let name = try hashMountSource(source: self.source)\n let urlSource = URL(fileURLWithPath: source)\n\n let device = VZVirtioFileSystemDeviceConfiguration(tag: name)\n device.share = VZSingleDirectoryShare(\n directory: VZSharedDirectory(\n url: urlSource,\n readOnly: readonly\n )\n )\n config.directorySharingDevices.append(device)\n case .any:\n break\n }\n }\n}\n\nextension VZDiskImageStorageDeviceAttachment {\n static func mountToVZAttachment(mount: Mount, options: [String]) throws -> VZDiskImageStorageDeviceAttachment {\n var cachingMode: VZDiskImageCachingMode = .automatic\n var synchronizationMode: VZDiskImageSynchronizationMode = .none\n\n for option in options {\n let split = option.split(separator: \"=\")\n if split.count != 2 {\n continue\n }\n\n let key = String(split[0])\n let value = String(split[1])\n\n switch key {\n case \"vzDiskImageCachingMode\":\n switch value {\n case \"automatic\":\n cachingMode = .automatic\n case \"cached\":\n cachingMode = .cached\n case \"uncached\":\n cachingMode = .uncached\n default:\n throw ContainerizationError(\n .invalidArgument,\n message: \"unknown vzDiskImageCachingMode value for virtio block device: \\(value)\"\n )\n }\n case \"vzDiskImageSynchronizationMode\":\n switch value {\n case \"full\":\n synchronizationMode = .full\n case \"fsync\":\n synchronizationMode = .fsync\n case \"none\":\n synchronizationMode = .none\n default:\n throw ContainerizationError(\n .invalidArgument,\n message: \"unknown vzDiskImageSynchronizationMode value for virtio block device: \\(value)\"\n )\n }\n default:\n throw ContainerizationError(\n .invalidArgument,\n message: \"unknown vmm option encountered: \\(key)\"\n )\n }\n }\n return try VZDiskImageStorageDeviceAttachment(\n url: URL(filePath: mount.source),\n readOnly: mount.readonly,\n cachingMode: cachingMode,\n synchronizationMode: synchronizationMode\n )\n }\n}\n\n#endif\n\nextension Mount {\n fileprivate var readonly: Bool {\n self.options.contains(\"ro\")\n }\n}\n"], ["/containerization/Sources/Containerization/Image/ImageStore/ImageStore+Export.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationIO\nimport ContainerizationOCI\nimport Crypto\nimport Foundation\n\nextension ImageStore {\n internal struct ExportOperation {\n let name: String\n let tag: String\n let contentStore: ContentStore\n let client: ContentClient\n let progress: ProgressHandler?\n\n init(name: String, tag: String, contentStore: ContentStore, client: ContentClient, progress: ProgressHandler? = nil) {\n self.contentStore = contentStore\n self.client = client\n self.progress = progress\n self.name = name\n self.tag = tag\n }\n\n @discardableResult\n internal func export(index: Descriptor, platforms: (Platform) -> Bool) async throws -> Descriptor {\n var pushQueue: [[Descriptor]] = []\n var current: [Descriptor] = [index]\n while !current.isEmpty {\n let children = try await self.getChildren(descs: current)\n let matches = try filterPlatforms(matcher: platforms, children).uniqued { $0.digest }\n pushQueue.append(matches)\n current = matches\n }\n let localIndexData = try await self.createIndex(from: index, matching: platforms)\n\n await updatePushProgress(pushQueue: pushQueue, localIndexData: localIndexData)\n\n // We need to work bottom up when pushing an image.\n // First, the tar blobs / config layers, then, the manifests and so on...\n // When processing a given \"level\", the requests maybe made in parallel.\n // We need to ensure that the child level has been uploaded fully\n // before uploading the parent level.\n try await withThrowingTaskGroup(of: Void.self) { group in\n for layerGroup in pushQueue.reversed() {\n for chunk in layerGroup.chunks(ofCount: 8) {\n for desc in chunk {\n guard let content = try await self.contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(desc.digest)\")\n }\n group.addTask {\n let readStream = try ReadStream(url: content.path)\n try await self.pushContent(descriptor: desc, stream: readStream)\n }\n }\n try await group.waitForAll()\n }\n }\n }\n\n // Lastly, we need to construct and push a new index, since we may\n // have pushed content only for specific platforms.\n let digest = SHA256.hash(data: localIndexData)\n let descriptor = Descriptor(\n mediaType: MediaTypes.index,\n digest: digest.digestString,\n size: Int64(localIndexData.count))\n let stream = ReadStream(data: localIndexData)\n try await self.pushContent(descriptor: descriptor, stream: stream)\n return descriptor\n }\n\n private func updatePushProgress(pushQueue: [[Descriptor]], localIndexData: Data) async {\n for layerGroup in pushQueue {\n for desc in layerGroup {\n await progress?([\n ProgressEvent(event: \"add-total-size\", value: desc.size),\n ProgressEvent(event: \"add-total-items\", value: 1),\n ])\n }\n }\n await progress?([\n ProgressEvent(event: \"add-total-size\", value: localIndexData.count),\n ProgressEvent(event: \"add-total-items\", value: 1),\n ])\n }\n\n private func createIndex(from index: Descriptor, matching: (Platform) -> Bool) async throws -> Data {\n guard let content = try await self.contentStore.get(digest: index.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(index.digest)\")\n }\n var idx: Index = try content.decode()\n let manifests = idx.manifests\n var matchedManifests: [Descriptor] = []\n var skippedPlatforms = false\n for manifest in manifests {\n guard let p = manifest.platform else {\n continue\n }\n if matching(p) {\n matchedManifests.append(manifest)\n } else {\n skippedPlatforms = true\n }\n }\n if !skippedPlatforms {\n return try content.data()\n }\n idx.manifests = matchedManifests\n return try JSONEncoder().encode(idx)\n }\n\n private func pushContent(descriptor: Descriptor, stream: ReadStream) async throws {\n do {\n let generator = {\n try stream.reset()\n return stream.stream\n }\n try await client.push(name: name, ref: tag, descriptor: descriptor, streamGenerator: generator, progress: progress)\n await progress?([\n ProgressEvent(event: \"add-size\", value: descriptor.size),\n ProgressEvent(event: \"add-items\", value: 1),\n ])\n } catch let err as ContainerizationError {\n guard err.code != .exists else {\n // We reported the total items and size and have to account for them in existing content.\n await progress?([\n ProgressEvent(event: \"add-size\", value: descriptor.size),\n ProgressEvent(event: \"add-items\", value: 1),\n ])\n return\n }\n throw err\n }\n }\n\n private func getChildren(descs: [Descriptor]) async throws -> [Descriptor] {\n var out: [Descriptor] = []\n for desc in descs {\n let mediaType = desc.mediaType\n guard let content = try await self.contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(desc.digest)\")\n }\n switch mediaType {\n case MediaTypes.index, MediaTypes.dockerManifestList:\n let index: Index = try content.decode()\n out.append(contentsOf: index.manifests)\n case MediaTypes.imageManifest, MediaTypes.dockerManifest:\n let manifest: Manifest = try content.decode()\n out.append(manifest.config)\n out.append(contentsOf: manifest.layers)\n default:\n continue\n }\n }\n return out\n }\n }\n}\n"], ["/containerization/Sources/Containerization/UnixSocketRelay.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationIO\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport Synchronization\n\npackage actor UnixSocketRelayManager {\n private let vm: any VirtualMachineInstance\n private var relays: [String: SocketRelay]\n private let q: DispatchQueue\n private let log: Logger?\n\n init(vm: any VirtualMachineInstance, log: Logger? = nil) {\n self.vm = vm\n self.relays = [:]\n self.q = DispatchQueue(label: \"com.apple.containerization.socket-relay\")\n self.log = log\n }\n}\n\nextension UnixSocketRelayManager {\n func start(port: UInt32, socket: UnixSocketConfiguration) async throws {\n guard self.relays[socket.id] == nil else {\n throw ContainerizationError(\n .invalidState,\n message: \"socket relay \\(socket.id) already started\"\n )\n }\n\n let socketRelay = try SocketRelay(\n port: port,\n socket: socket,\n vm: self.vm,\n queue: self.q,\n log: self.log\n )\n\n do {\n self.relays[socket.id] = socketRelay\n try await socketRelay.start()\n } catch {\n self.relays.removeValue(forKey: socket.id)\n }\n }\n\n func stop(socket: UnixSocketConfiguration) async throws {\n guard let storedRelay = self.relays.removeValue(forKey: socket.id) else {\n throw ContainerizationError(\n .notFound,\n message: \"failed to stop socket relay\"\n )\n }\n try storedRelay.stop()\n }\n\n func stopAll() async throws {\n for (_, relay) in self.relays {\n try relay.stop()\n }\n }\n}\n\npackage final class SocketRelay: Sendable {\n private let port: UInt32\n private let configuration: UnixSocketConfiguration\n private let log: Logger?\n private let vm: any VirtualMachineInstance\n private let q: DispatchQueue\n private let state: Mutex\n\n private struct State {\n var relaySources: [String: ConnectionSources] = [:]\n var t: Task<(), Never>? = nil\n }\n\n // `DispatchSourceRead` is thread-safe.\n private struct ConnectionSources: @unchecked Sendable {\n let hostSource: DispatchSourceRead\n let guestSource: DispatchSourceRead\n }\n\n init(\n port: UInt32,\n socket: UnixSocketConfiguration,\n vm: any VirtualMachineInstance,\n queue: DispatchQueue,\n log: Logger? = nil\n ) throws {\n self.port = port\n self.configuration = socket\n self.state = Mutex(.init())\n self.vm = vm\n self.log = log\n self.q = queue\n }\n\n deinit {\n self.state.withLock { $0.t?.cancel() }\n }\n}\n\nextension SocketRelay {\n func start() async throws {\n switch configuration.direction {\n case .outOf:\n try await setupHostVsockDial()\n case .into:\n try setupHostVsockListener()\n }\n }\n\n func stop() throws {\n try self.state.withLock {\n guard let t = $0.t else {\n throw ContainerizationError(\n .invalidState,\n message: \"failed to stop socket relay: relay has not been started\"\n )\n }\n t.cancel()\n $0.t = nil\n $0.relaySources.removeAll()\n }\n\n switch configuration.direction {\n case .outOf:\n // If we created the host conn, lets unlink it also. It's possible it was\n // already unlinked if the relay failed earlier.\n try? FileManager.default.removeItem(at: self.configuration.destination)\n case .into:\n try self.vm.stopListen(self.port)\n }\n }\n\n private func setupHostVsockDial() async throws {\n let hostConn = self.configuration.destination\n\n let socketType = try UnixType(\n path: hostConn.path,\n unlinkExisting: true\n )\n let hostSocket = try Socket(type: socketType)\n try hostSocket.listen()\n\n let connectionStream = try hostSocket.acceptStream(closeOnDeinit: false)\n self.state.withLock {\n $0.t = Task {\n do {\n for try await connection in connectionStream {\n try await self.handleHostUnixConn(\n hostConn: connection,\n port: self.port,\n vm: self.vm,\n log: self.log\n )\n }\n } catch {\n log?.error(\"failed in unix socket relay loop: \\(error)\")\n }\n try? FileManager.default.removeItem(at: hostConn)\n }\n }\n }\n\n private func setupHostVsockListener() throws {\n let hostPath = self.configuration.source\n let port = self.port\n let log = self.log\n\n let connectionStream = try self.vm.listen(self.port)\n self.state.withLock {\n $0.t = Task {\n do {\n defer { connectionStream.finish() }\n for await connection in connectionStream.connections {\n try await self.handleGuestVsockConn(\n vsockConn: connection,\n hostConnectionPath: hostPath,\n port: port,\n log: log\n )\n }\n } catch {\n log?.error(\"failed to setup relay between vsock \\(port) and \\(hostPath.path): \\(error)\")\n }\n }\n }\n }\n\n private func handleHostUnixConn(\n hostConn: ContainerizationOS.Socket,\n port: UInt32,\n vm: any VirtualMachineInstance,\n log: Logger?\n ) async throws {\n do {\n let guestConn = try await vm.dial(port)\n try await self.relay(\n hostConn: hostConn,\n guestFd: guestConn.fileDescriptor\n )\n } catch {\n log?.error(\"failed to relay between vsock \\(port) and \\(hostConn)\")\n throw error\n }\n }\n\n private func handleGuestVsockConn(\n vsockConn: FileHandle,\n hostConnectionPath: URL,\n port: UInt32,\n log: Logger?\n ) async throws {\n let hostPath = hostConnectionPath.path\n let socketType = try UnixType(path: hostPath)\n let hostSocket = try Socket(\n type: socketType,\n closeOnDeinit: false\n )\n try hostSocket.connect()\n\n do {\n try await self.relay(\n hostConn: hostSocket,\n guestFd: vsockConn.fileDescriptor\n )\n } catch {\n log?.error(\"failed to relay between vsock \\(port) and \\(hostPath)\")\n }\n }\n\n private func relay(\n hostConn: Socket,\n guestFd: Int32\n ) async throws {\n let connSource = DispatchSource.makeReadSource(\n fileDescriptor: hostConn.fileDescriptor,\n queue: self.q\n )\n let vsockConnectionSource = DispatchSource.makeReadSource(\n fileDescriptor: guestFd,\n queue: self.q\n )\n\n let pairID = UUID().uuidString\n self.state.withLock {\n $0.relaySources[pairID] = ConnectionSources(\n hostSource: connSource,\n guestSource: vsockConnectionSource\n )\n }\n\n nonisolated(unsafe) let buf1 = UnsafeMutableBufferPointer.allocate(capacity: Int(getpagesize()))\n connSource.setEventHandler {\n Self.fdCopyHandler(\n buffer: buf1,\n source: connSource,\n from: hostConn.fileDescriptor,\n to: guestFd\n )\n }\n\n nonisolated(unsafe) let buf2 = UnsafeMutableBufferPointer.allocate(capacity: Int(getpagesize()))\n vsockConnectionSource.setEventHandler {\n Self.fdCopyHandler(\n buffer: buf2,\n source: vsockConnectionSource,\n from: guestFd,\n to: hostConn.fileDescriptor\n )\n }\n\n connSource.setCancelHandler {\n if !connSource.isCancelled {\n connSource.cancel()\n }\n if !vsockConnectionSource.isCancelled {\n vsockConnectionSource.cancel()\n }\n try? hostConn.close()\n }\n\n vsockConnectionSource.setCancelHandler {\n if !vsockConnectionSource.isCancelled {\n vsockConnectionSource.cancel()\n }\n if !connSource.isCancelled {\n connSource.cancel()\n }\n close(guestFd)\n }\n\n connSource.activate()\n vsockConnectionSource.activate()\n }\n\n private static func fdCopyHandler(\n buffer: UnsafeMutableBufferPointer,\n source: DispatchSourceRead,\n from sourceFd: Int32,\n to destinationFd: Int32,\n log: Logger? = nil\n ) {\n if source.data == 0 {\n if !source.isCancelled {\n source.cancel()\n }\n return\n }\n\n do {\n try self.fileDescriptorCopy(\n buffer: buffer,\n size: source.data,\n from: sourceFd,\n to: destinationFd\n )\n } catch {\n log?.error(\"file descriptor copy failed \\(error)\")\n if !source.isCancelled {\n source.cancel()\n }\n }\n }\n\n private static func fileDescriptorCopy(\n buffer: UnsafeMutableBufferPointer,\n size: UInt,\n from sourceFd: Int32,\n to destinationFd: Int32\n ) throws {\n let bufferSize = buffer.count\n var readBytesRemaining = min(Int(size), bufferSize)\n\n guard let baseAddr = buffer.baseAddress else {\n throw ContainerizationError(\n .invalidState,\n message: \"buffer has no base address\"\n )\n }\n\n while readBytesRemaining > 0 {\n let readResult = read(sourceFd, baseAddr, min(bufferSize, readBytesRemaining))\n if readResult <= 0 {\n throw ContainerizationError(\n .internalError,\n message: \"missing pointer base address\"\n )\n }\n readBytesRemaining -= readResult\n\n var writeBytesRemaining = readResult\n while writeBytesRemaining > 0 {\n let writeResult = write(destinationFd, baseAddr, writeBytesRemaining)\n if writeResult <= 0 {\n throw ContainerizationError(\n .internalError,\n message: \"zero byte write or error in socket relay\"\n )\n }\n writeBytesRemaining -= writeResult\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/RegistryClient+Fetch.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport ContainerizationError\nimport ContainerizationExtras\nimport Crypto\nimport Foundation\nimport NIOFoundationCompat\n\n#if os(macOS)\nimport NIOFileSystem\n#endif\n\nextension RegistryClient {\n /// Resolve sends a HEAD request to the registry to find root manifest descriptor.\n /// This descriptor serves as an entry point to retrieve resources from the registry.\n public func resolve(name: String, tag: String) async throws -> Descriptor {\n var components = base\n\n // Make HEAD request to retrieve the digest header\n components.path = \"/v2/\\(name)/manifests/\\(tag)\"\n\n // The client should include an Accept header indicating which manifest content types it supports.\n let mediaTypes = [\n MediaTypes.dockerManifest,\n MediaTypes.dockerManifestList,\n MediaTypes.imageManifest,\n MediaTypes.index,\n \"*/*\",\n ]\n\n let headers = [\n (\"Accept\", mediaTypes.joined(separator: \", \"))\n ]\n\n return try await request(components: components, method: .HEAD, headers: headers) { response in\n guard response.status == .ok else {\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n\n guard let digest = response.headers.first(name: \"Docker-Content-Digest\") else {\n throw ContainerizationError(.invalidArgument, message: \"Missing required header Docker-Content-Digest\")\n }\n\n guard let type = response.headers.first(name: \"Content-Type\") else {\n throw ContainerizationError(.invalidArgument, message: \"Missing required header Content-Type\")\n }\n\n guard let sizeStr = response.headers.first(name: \"Content-Length\") else {\n throw ContainerizationError(.invalidArgument, message: \"Missing required header Content-Length\")\n }\n\n guard let size = Int64(sizeStr) else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot convert \\(sizeStr) to Int64\")\n }\n\n return Descriptor(mediaType: type, digest: digest, size: size)\n }\n }\n\n /// Fetch resource (either manifest or blob) to memory with JSON decoding.\n public func fetch(name: String, descriptor: Descriptor) async throws -> T {\n var components = base\n\n let manifestTypes = [\n MediaTypes.dockerManifest,\n MediaTypes.dockerManifestList,\n MediaTypes.imageManifest,\n MediaTypes.index,\n ]\n\n let isManifest = manifestTypes.contains(where: { $0 == descriptor.mediaType })\n let resource = isManifest ? \"manifests\" : \"blobs\"\n\n components.path = \"/v2/\\(name)/\\(resource)/\\(descriptor.digest)\"\n\n let mediaType = descriptor.mediaType\n if mediaType.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Missing media type for descriptor \\(descriptor.digest)\")\n }\n\n let headers = [\n (\"Accept\", mediaType)\n ]\n\n return try await requestJSON(components: components, headers: headers)\n }\n\n /// Fetch resource (either manifest or blob) to memory as raw `Data`.\n public func fetchData(name: String, descriptor: Descriptor) async throws -> Data {\n var components = base\n\n let manifestTypes = [\n MediaTypes.dockerManifest,\n MediaTypes.dockerManifestList,\n MediaTypes.imageManifest,\n MediaTypes.index,\n ]\n\n let isManifest = manifestTypes.contains(where: { $0 == descriptor.mediaType })\n let resource = isManifest ? \"manifests\" : \"blobs\"\n\n components.path = \"/v2/\\(name)/\\(resource)/\\(descriptor.digest)\"\n\n let mediaType = descriptor.mediaType\n if mediaType.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Missing media type for descriptor \\(descriptor.digest)\")\n }\n\n let headers = [\n (\"Accept\", mediaType)\n ]\n\n return try await requestData(components: components, headers: headers)\n }\n\n /// Fetch a blob from remote registry.\n /// This method is suitable for streaming data.\n public func fetchBlob(\n name: String,\n descriptor: Descriptor,\n closure: (Int64, HTTPClientResponse.Body) async throws -> Void\n ) async throws {\n var components = base\n components.path = \"/v2/\\(name)/blobs/\\(descriptor.digest)\"\n\n let mediaType = descriptor.mediaType\n if mediaType.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Missing media type for descriptor \\(descriptor.digest)\")\n }\n\n let headers = [\n (\"Accept\", mediaType)\n ]\n\n try await request(components: components, headers: headers) { response in\n guard response.status == .ok else {\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n\n // How many bytes to expect\n guard let expectedBytes = response.headers.first(name: \"Content-Length\").flatMap(Int64.init) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing required header Content-Length\")\n }\n\n try await closure(expectedBytes, response.body)\n }\n }\n\n #if os(macOS)\n /// Fetch a blob from remote registry and write the contents into a file in the provided directory.\n public func fetchBlob(name: String, descriptor: Descriptor, into file: URL, progress: ProgressHandler?) async throws -> (Int64, SHA256Digest) {\n var hasher = SHA256()\n var received: Int64 = 0\n let fs = NIOFileSystem.FileSystem.shared\n let handle = try await fs.openFile(forWritingAt: FilePath(file.absolutePath()), options: .newFile(replaceExisting: true))\n var writer = handle.bufferedWriter()\n do {\n try await self.fetchBlob(name: name, descriptor: descriptor) { (size, body) in\n var itr = body.makeAsyncIterator()\n while let buf = try await itr.next() {\n let readBytes = Int64(buf.readableBytes)\n received += readBytes\n let written = try await writer.write(contentsOf: buf)\n await progress?([\n ProgressEvent(event: \"add-size\", value: written)\n ])\n guard written == readBytes else {\n throw ContainerizationError(\n .internalError,\n message: \"Could not write \\(readBytes) bytes to file \\(file)\"\n )\n }\n hasher.update(data: buf.readableBytesView)\n }\n }\n try await writer.flush()\n try await handle.close()\n } catch {\n try? await handle.close()\n throw error\n }\n let computedDigest = hasher.finalize()\n return (received, computedDigest)\n }\n #else\n /// Fetch a blob from remote registry and write the contents into a file in the provided directory.\n public func fetchBlob(name: String, descriptor: Descriptor, into file: URL, progress: ProgressHandler?) async throws -> (Int64, SHA256Digest) {\n var hasher = SHA256()\n var received: Int64 = 0\n guard FileManager.default.createFile(atPath: file.path, contents: nil) else {\n throw ContainerizationError(.internalError, message: \"Cannot create file at path \\(file.path)\")\n }\n try await self.fetchBlob(name: name, descriptor: descriptor) { (size, body) in\n let fd = try FileHandle(forWritingTo: file)\n defer {\n try? fd.close()\n }\n var itr = body.makeAsyncIterator()\n while let buf = try await itr.next() {\n let readBytes = Int64(buf.readableBytes)\n received += readBytes\n await progress?([\n ProgressEvent(event: \"add-size\", value: readBytes)\n ])\n try fd.write(contentsOf: buf.readableBytesView)\n hasher.update(data: buf.readableBytesView)\n }\n }\n let computedDigest = hasher.finalize()\n return (received, computedDigest)\n }\n #endif\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/LocalContentStore.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// swiftlint:disable unused_optional_binding\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport Crypto\nimport Foundation\n\n/// A `ContentStore` implementation that stores content on the local filesystem.\npublic actor LocalContentStore: ContentStore {\n private static let encoder = JSONEncoder()\n\n private let _basePath: URL\n private let _ingestPath: URL\n private let _blobPath: URL\n private let _lock: AsyncLock\n\n private var activeIngestSessions: AsyncSet = AsyncSet([])\n\n /// Create a new `LocalContentStore`.\n ///\n /// - Parameters:\n /// - path: The path where content should be written under.\n public init(path: URL) throws {\n let ingestPath = path.appendingPathComponent(\"ingest\")\n let blobPath = path.appendingPathComponent(\"blobs/sha256\")\n\n let fileManager = FileManager.default\n try fileManager.createDirectory(at: ingestPath, withIntermediateDirectories: true)\n try fileManager.createDirectory(at: blobPath, withIntermediateDirectories: true)\n\n self._basePath = path\n self._ingestPath = ingestPath\n self._blobPath = blobPath\n self._lock = AsyncLock()\n Self.encoder.outputFormatting = .sortedKeys\n }\n\n /// Get a piece of content from the store. Returns nil if not\n /// found.\n ///\n /// - Parameters:\n /// - digest: The string digest of the content.\n public func get(digest: String) throws -> Content? {\n let d = digest.trimmingDigestPrefix\n let path = self._blobPath.appendingPathComponent(d)\n do {\n return try LocalContent(path: path)\n } catch let err as ContainerizationError {\n switch err.code {\n case .notFound:\n return nil\n default:\n throw err\n }\n }\n }\n\n /// Get a piece of content from the store and return the decoded version of\n /// it.\n ///\n /// - Parameters:\n /// - digest: The string digest of the content.\n public func get(digest: String) throws -> T? {\n guard let content: Content = try self.get(digest: digest) else {\n return nil\n }\n return try content.decode()\n }\n\n /// Delete all content besides a set provided.\n ///\n /// - Parameters:\n /// - keeping: The set of string digests to keep.\n public func delete(keeping: [String]) async throws -> ([String], UInt64) {\n let fileManager = FileManager.default\n let all = try fileManager.contentsOfDirectory(at: self._blobPath, includingPropertiesForKeys: nil)\n let allDigests = Set(all.map { $0.lastPathComponent })\n let toDelete = allDigests.subtracting(keeping)\n return try await self.delete(digests: Array(toDelete))\n }\n\n /// Delete a specific set of content.\n ///\n /// - Parameters:\n /// - digests: Array of strings denoting the digests of the content to delete.\n @discardableResult\n public func delete(digests: [String]) async throws -> ([String], UInt64) {\n let store = AsyncStore<([String], UInt64)>()\n try await self._lock.withLock { context in\n let fileManager = FileManager.default\n var deleted: [String] = []\n var deletedBytes: UInt64 = 0\n for toDelete in digests {\n let p = self._blobPath.appendingPathComponent(toDelete)\n guard let content = try? LocalContent(path: p) else {\n continue\n }\n deletedBytes += try content.size()\n try fileManager.removeItem(at: p)\n deleted.append(toDelete)\n }\n await store.set((deleted, deletedBytes))\n }\n return await store.get() ?? ([], 0)\n }\n\n /// Creates a transactional write to the content store.\n ///\n /// - Parameters:\n /// - body: Closure that is given a temporary `URL` of the base directory which all contents should be written to.\n /// This is a transaction write where any failed operation in the closure (caught exception) will result in all contents written\n /// in the closure to be deleted. If the closure succeeds, then all the content that have been written to the temporary `URL`\n /// will be moved into the actual blobs path of the content store.\n @discardableResult\n public func ingest(_ body: @Sendable @escaping (URL) async throws -> Void) async throws -> [String] {\n let (id, tempPath) = try await self.newIngestSession()\n try await body(tempPath)\n return try await self.completeIngestSession(id)\n }\n\n /// Creates a new ingest session and returns the session ID and temporary ingest directory corresponding to the session.\n /// The contents from the ingest directory are processed and moved into the content store once the session is marked complete.\n /// This can be done by invoking the `completeIngestSession` method with the returned session ID.\n public func newIngestSession() async throws -> (id: String, ingestDir: URL) {\n let id = UUID().uuidString\n let temporaryPath = self._ingestPath.appendingPathComponent(id)\n let fileManager = FileManager.default\n try fileManager.createDirectory(atPath: temporaryPath.path, withIntermediateDirectories: true)\n await self.activeIngestSessions.insert(id)\n return (id, temporaryPath)\n }\n\n /// Completes a previously started ingest session corresponding to `id`. The contents from the ingest\n /// directory from the session are moved into the content store atomically. Any failure encountered will\n /// result in a transaction failure causing none of the contents to be ingested into the store.\n /// - Parameters:\n /// - id: id of the ingest session to complete.\n @discardableResult\n public func completeIngestSession(_ id: String) async throws -> [String] {\n guard await activeIngestSessions.contains(id) else {\n throw ContainerizationError(.internalError, message: \"Invalid session id \\(id)\")\n }\n await activeIngestSessions.remove(id)\n let temporaryPath = self._ingestPath.appendingPathComponent(id)\n let fileManager = FileManager.default\n defer {\n try? fileManager.removeItem(at: temporaryPath)\n }\n let tempDigests: [URL] = try fileManager.contentsOfDirectory(at: temporaryPath, includingPropertiesForKeys: nil)\n return try await self._lock.withLock { context in\n var moved: [String] = []\n let fileManager = FileManager.default\n do {\n try tempDigests.forEach {\n let digest = $0.lastPathComponent\n let target = self._blobPath.appendingPathComponent(digest)\n // only ingest if not exists\n if !fileManager.fileExists(atPath: target.path) {\n try fileManager.moveItem(at: $0, to: target)\n moved.append(digest)\n }\n }\n } catch {\n moved.forEach {\n try? fileManager.removeItem(at: self._blobPath.appendingPathComponent($0))\n }\n throw error\n }\n return tempDigests.map { $0.lastPathComponent }\n }\n }\n\n /// Cancels a previously started ingest session corresponding to `id`.\n /// The contents from the ingest directory corresponding to the session are removed.\n /// - Parameters:\n /// - id: id of the ingest session to complete.\n public func cancelIngestSession(_ id: String) async throws {\n guard let _ = await self.activeIngestSessions.remove(id) else {\n return\n }\n let temporaryPath = self._ingestPath.appendingPathComponent(id)\n let fileManager = FileManager.default\n try? fileManager.removeItem(at: temporaryPath)\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Mount/Mount.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n#if canImport(Musl)\nimport Musl\nprivate let _mount = Musl.mount\nprivate let _umount = Musl.umount2\n#elseif canImport(Glibc)\nimport Glibc\nprivate let _mount = Glibc.mount\nprivate let _umount = Glibc.umount2\n#endif\n\n// Mount package modeled closely from containerd's: https://github.com/containerd/containerd/tree/main/core/mount\n\n/// `Mount` models a Linux mount (although potentially could be used on other unix platforms), and\n/// provides a simple interface to mount what the type describes.\npublic struct Mount: Sendable {\n // Type specifies the host-specific of the mount.\n public var type: String\n // Source specifies where to mount from. Depending on the host system, this\n // can be a source path or device.\n public var source: String\n // Target specifies an optional subdirectory as a mountpoint.\n public var target: String\n // Options contains zero or more fstab-style mount options.\n public var options: [String]\n\n public init(type: String, source: String, target: String, options: [String]) {\n self.type = type\n self.source = source\n self.target = target\n self.options = options\n }\n}\n\nextension Mount {\n internal struct FlagBehavior {\n let clear: Bool\n let flag: Int32\n\n public init(_ clear: Bool, _ flag: Int32) {\n self.clear = clear\n self.flag = flag\n }\n }\n\n #if os(Linux)\n internal static let flagsDictionary: [String: FlagBehavior] = [\n \"async\": .init(true, MS_SYNCHRONOUS),\n \"atime\": .init(true, MS_NOATIME),\n \"bind\": .init(false, MS_BIND),\n \"defaults\": .init(false, 0),\n \"dev\": .init(true, MS_NODEV),\n \"diratime\": .init(true, MS_NODIRATIME),\n \"dirsync\": .init(false, MS_DIRSYNC),\n \"exec\": .init(true, MS_NOEXEC),\n \"mand\": .init(false, MS_MANDLOCK),\n \"noatime\": .init(false, MS_NOATIME),\n \"nodev\": .init(false, MS_NODEV),\n \"nodiratime\": .init(false, MS_NODIRATIME),\n \"noexec\": .init(false, MS_NOEXEC),\n \"nomand\": .init(true, MS_MANDLOCK),\n \"norelatime\": .init(true, MS_RELATIME),\n \"nostrictatime\": .init(true, MS_STRICTATIME),\n \"nosuid\": .init(false, MS_NOSUID),\n \"rbind\": .init(false, MS_BIND | MS_REC),\n \"relatime\": .init(false, MS_RELATIME),\n \"remount\": .init(false, MS_REMOUNT),\n \"ro\": .init(false, MS_RDONLY),\n \"rw\": .init(true, MS_RDONLY),\n \"strictatime\": .init(false, MS_STRICTATIME),\n \"suid\": .init(true, MS_NOSUID),\n \"sync\": .init(false, MS_SYNCHRONOUS),\n ]\n\n internal struct MountOptions {\n var flags: Int32\n var data: [String]\n\n public init(_ flags: Int32 = 0, data: [String] = []) {\n self.flags = flags\n self.data = data\n }\n }\n\n /// Whether the mount is read only.\n public var readOnly: Bool {\n for option in self.options {\n if option == \"ro\" {\n return true\n }\n }\n return false\n }\n\n /// Mount the mount relative to `root` with the current set of data in the object.\n /// Optionally provide `createWithPerms` to set the permissions for the directory that\n /// it will be mounted at.\n public func mount(root: String, createWithPerms: Int16? = nil) throws {\n var rootURL = URL(fileURLWithPath: root)\n rootURL = rootURL.resolvingSymlinksInPath()\n rootURL = rootURL.appendingPathComponent(self.target)\n try self.mountToTarget(target: rootURL.path, createWithPerms: createWithPerms)\n }\n\n /// Mount the mount with the current set of data in the object. Optionally\n /// provide `createWithPerms` to set the permissions for the directory that\n /// it will be mounted at.\n public func mount(createWithPerms: Int16? = nil) throws {\n try self.mountToTarget(target: self.target, createWithPerms: createWithPerms)\n }\n\n private func mountToTarget(target: String, createWithPerms: Int16?) throws {\n let pageSize = sysconf(_SC_PAGESIZE)\n\n let opts = parseMountOptions()\n let dataString = opts.data.joined(separator: \",\")\n if dataString.count > pageSize {\n throw Error.validation(\"data string exceeds page size (\\(dataString.count) > \\(pageSize))\")\n }\n\n let propagationTypes: Int32 = MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE\n\n // Ensure propagation type change flags aren't included in other calls.\n let originalFlags = opts.flags & ~(propagationTypes)\n\n let targetURL = URL(fileURLWithPath: self.target)\n let targetParent = targetURL.deletingLastPathComponent().path\n if let perms = createWithPerms {\n try mkdirAll(targetParent, perms)\n }\n try mkdirAll(target, 0o755)\n\n if opts.flags & MS_REMOUNT == 0 || !dataString.isEmpty {\n guard _mount(self.source, target, self.type, UInt(originalFlags), dataString) == 0 else {\n throw Error.errno(\n errno,\n \"failed initial mount source=\\(self.source) target=\\(target) type=\\(self.type) data=\\(dataString)\"\n )\n }\n }\n\n if opts.flags & propagationTypes != 0 {\n // Change the propagation type.\n let pflags = propagationTypes | MS_REC | MS_SILENT\n guard _mount(\"\", target, \"\", UInt(opts.flags & pflags), \"\") == 0 else {\n throw Error.errno(errno, \"failed propagation change mount\")\n }\n }\n\n let bindReadOnlyFlags = MS_BIND | MS_RDONLY\n if originalFlags & bindReadOnlyFlags == bindReadOnlyFlags {\n guard _mount(\"\", target, \"\", UInt(originalFlags | MS_REMOUNT), \"\") == 0 else {\n throw Error.errno(errno, \"failed bind mount\")\n }\n }\n }\n\n private func mkdirAll(_ name: String, _ perm: Int16) throws {\n try FileManager.default.createDirectory(\n atPath: name,\n withIntermediateDirectories: true,\n attributes: [.posixPermissions: perm]\n )\n }\n\n private func parseMountOptions() -> MountOptions {\n var mountOpts = MountOptions()\n for option in self.options {\n if let entry = Self.flagsDictionary[option], entry.flag != 0 {\n if entry.clear {\n mountOpts.flags &= ~entry.flag\n } else {\n mountOpts.flags |= entry.flag\n }\n } else {\n mountOpts.data.append(option)\n }\n }\n return mountOpts\n }\n\n /// `Mount` errors\n public enum Error: Swift.Error, CustomStringConvertible {\n case errno(Int32, String)\n case validation(String)\n\n public var description: String {\n switch self {\n case .errno(let errno, let message):\n return \"mount failed with errno \\(errno): \\(message)\"\n case .validation(let message):\n return \"failed during validation: \\(message)\"\n }\n }\n }\n #endif\n}\n"], ["/containerization/Sources/Containerization/Image/ImageStore/ImageStore.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\n/// An ImageStore handles the mappings between an image's\n/// reference and the underlying descriptor inside of a content store.\npublic actor ImageStore: Sendable {\n /// The ImageStore path it was created with.\n public nonisolated let path: URL\n\n private let referenceManager: ReferenceManager\n internal let contentStore: ContentStore\n internal let lock: AsyncLock = AsyncLock()\n\n public init(path: URL, contentStore: ContentStore? = nil) throws {\n try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true)\n\n if let contentStore {\n self.contentStore = contentStore\n } else {\n self.contentStore = try LocalContentStore(path: path.appendingPathComponent(\"content\"))\n }\n\n self.path = path\n self.referenceManager = try ReferenceManager(path: path)\n }\n\n /// Return the default image store for the current user.\n public static let `default`: ImageStore = {\n do {\n let root = try defaultRoot()\n return try ImageStore(path: root)\n } catch {\n fatalError(\"unable to initialize default ImageStore \\(error)\")\n }\n }()\n\n private static func defaultRoot() throws -> URL {\n let root = FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first\n guard let root else {\n throw ContainerizationError(.notFound, message: \"unable to get Application Support directory for current user\")\n }\n return root.appendingPathComponent(\"com.apple.containerization\")\n\n }\n}\n\nextension ImageStore {\n /// Get an image from the `ImageStore`.\n ///\n /// - Parameters:\n /// - reference: Name of the image.\n /// - pull: Pull the image if it is not found.\n ///\n /// - Returns: A `Containerization.Image` object whose `reference` matches the given string.\n /// This method throws a `ContainerizationError(code: .notFound)` if the provided reference does not exist in the `ImageStore`.\n public func get(reference: String, pull: Bool = false) async throws -> Image {\n do {\n let desc = try await self.referenceManager.get(reference: reference)\n return Image(description: desc, contentStore: self.contentStore)\n } catch let error as ContainerizationError {\n if error.code == .notFound && pull {\n return try await self.pull(reference: reference)\n }\n throw error\n }\n }\n\n /// Get a list of all images in the `ImageStore`.\n ///\n /// - Returns: A `[Containerization.Image]` for all the images in the `ImageStore`.\n public func list() async throws -> [Image] {\n try await self.referenceManager.list().map { desc in\n Image(description: desc, contentStore: self.contentStore)\n }\n }\n\n /// Create a new image in the `ImageStore`.\n ///\n /// - Parameters:\n /// - description: The underlying `Image.Description` that contains information about the reference and index descriptor for the image to be created.\n ///\n /// - Note: It is assumed that the underlying manifests and blob layers for the image already exists in the `ContentStore` that the `ImageStore` was initialized with. This method is invoked when the `pull(...)` , `load(...)` and `tag(...)` methods are used.\n /// - Returns: A `Containerization.Image`\n @discardableResult\n internal func create(description: Image.Description) async throws -> Image {\n try await self.lock.withLock { ctx in\n try await self._create(description: description, lock: ctx)\n }\n }\n\n @discardableResult\n internal func _create(description: Image.Description, lock: AsyncLock.Context) async throws -> Image {\n try await self.referenceManager.create(description: description)\n return Image(description: description, contentStore: self.contentStore)\n }\n\n /// Delete an image from the `ImageStore`.\n ///\n /// - Parameters:\n /// - reference: Name of the image that is to be deleted.\n /// - performCleanup: Perform a garbage collection on the `ContentStore`, removing all unreferenced image layers and manifests,\n public func delete(reference: String, performCleanup: Bool = false) async throws {\n try await self.lock.withLock { lockCtx in\n try await self.referenceManager.delete(reference: reference)\n if performCleanup {\n try await self._prune(lockCtx)\n }\n }\n }\n\n /// Perform a garbage collection in the underlying `ContentStore` that is managed by the `ImageStore`.\n ///\n /// - Returns: Returns a tuple of `(deleted, freed)`.\n /// `deleted` : A list of the names of the content items that were deleted from the `ContentStore`,\n /// `freed` : The total size of the items that were deleted.\n @discardableResult\n public func prune() async throws -> (deleted: [String], freed: UInt64) {\n try await self.lock.withLock { lockCtx in\n try await self._prune(lockCtx)\n }\n }\n\n @discardableResult\n private func _prune(_ lock: AsyncLock.Context) async throws -> ([String], UInt64) {\n let images = try await self.list()\n var referenced: [String] = []\n for image in images {\n try await referenced.append(contentsOf: image.referencedDigests().uniqued())\n }\n let (deleted, size) = try await self.contentStore.delete(keeping: referenced)\n return (deleted, size)\n\n }\n\n /// Tag an existing image such that it can be referenced by another name.\n ///\n /// - Parameters:\n /// - existing: The reference to an image that already exists in the `ImageStore`.\n /// - new: The new reference by which the image should also be referenced as.\n /// - Note: The new image created in the `ImageStore` will have the same `Image.Description`\n /// as that of the image with reference `existing.`\n /// - Returns: A `Containerization.Image` object to the newly created image.\n public func tag(existing: String, new: String) async throws -> Image {\n let old = try await self.get(reference: existing)\n let descriptor = old.descriptor\n do {\n _ = try Reference.parse(new)\n } catch {\n throw ContainerizationError(.invalidArgument, message: \"Invalid reference \\(new). Error: \\(error)\")\n }\n let newDescription = Image.Description(reference: new, descriptor: descriptor)\n return try await self.create(description: newDescription)\n }\n}\n\nextension ImageStore {\n /// Pull an image and its associated manifest and blob layers from a remote registry.\n ///\n /// - Parameters:\n /// - reference: A string that references an image in a remote registry of the form `[:]/repository:`\n /// For example: \"docker.io/library/alpine:latest\".\n /// - platform: An optional parameter to indicate the platform to be pulled for the image.\n /// Defaults to `nil` signifying that layers for all supported platforms by the image will be pulled.\n /// - insecure: A boolean indicating if the connection to the remote registry should be made via plain-text http or not.\n /// Defaults to false, meaning the connection to the registry will be over https.\n /// - auth: An object that implements the `Authentication` protocol,\n /// used to add any credentials to the HTTP requests that are made to the registry.\n /// Defaults to `nil` meaning no additional credentials are added to any HTTP requests made to the registry.\n /// - progress: An optional handler over which progress update events about the pull operation can be received.\n ///\n /// - Returns: A `Containerization.Image` object to the newly pulled image.\n public func pull(\n reference: String, platform: Platform? = nil, insecure: Bool = false,\n auth: Authentication? = nil, progress: ProgressHandler? = nil\n ) async throws -> Image {\n\n let matcher = createPlatformMatcher(for: platform)\n let client = try RegistryClient(reference: reference, insecure: insecure, auth: auth)\n\n let ref = try Reference.parse(reference)\n let name = ref.path\n guard let tag = ref.tag ?? ref.digest else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid tag/digest for image reference \\(reference)\")\n }\n\n let rootDescriptor = try await client.resolve(name: name, tag: tag)\n let (id, tempDir) = try await self.contentStore.newIngestSession()\n let operation = ImportOperation(name: name, contentStore: self.contentStore, client: client, ingestDir: tempDir, progress: progress)\n do {\n let index = try await operation.import(root: rootDescriptor, matcher: matcher)\n return try await self.lock.withLock { lock in\n try await self.contentStore.completeIngestSession(id)\n let description = Image.Description(reference: reference, descriptor: index)\n let image = try await self._create(description: description, lock: lock)\n return image\n }\n } catch {\n try? await self.contentStore.cancelIngestSession(id)\n throw error\n }\n }\n\n /// Push an image and its associated manifest and blob layers to a remote registry.\n ///\n /// - Parameters:\n /// - reference: A string that references an image in the `ImageStore`. It must be of the form `[:]/repository:`\n /// For example: \"ghcr.io/foo-bar-baz/image:v1\".\n /// - platform: An optional parameter to indicate the platform to be pushed for the image.\n /// Defaults to `nil` signifying that layers for all supported platforms by the image will be pushed to the remote registry.\n /// - insecure: A boolean indicating if the connection to the remote registry should be made via plain-text http or not.\n /// Defaults to false, meaning the connection to the registry will be over https.\n /// - auth: An object that implements the `Authentication` protocol,\n /// used to add any credentials to the HTTP requests that are made to the registry.\n /// Defaults to `nil` meaning no additional credentials are added to any HTTP requests made to the registry.\n /// - progress: An optional handler over which progress update events about the push operation can be received.\n ///\n public func push(reference: String, platform: Platform? = nil, insecure: Bool = false, auth: Authentication? = nil, progress: ProgressHandler? = nil) async throws {\n let matcher = createPlatformMatcher(for: platform)\n let img = try await self.get(reference: reference)\n let allowedMediaTypes = [MediaTypes.dockerManifestList, MediaTypes.index]\n guard allowedMediaTypes.contains(img.mediaType) else {\n throw ContainerizationError(.internalError, message: \"Cannot push image \\(reference) with Index media type \\(img.mediaType)\")\n }\n let ref = try Reference.parse(reference)\n let name = ref.path\n guard let tag = ref.tag ?? ref.digest else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid tag/digest for image reference \\(reference)\")\n }\n let client = try RegistryClient(reference: reference, insecure: insecure, auth: auth)\n let operation = ExportOperation(name: name, tag: tag, contentStore: self.contentStore, client: client, progress: progress)\n try await operation.export(index: img.descriptor, platforms: matcher)\n }\n}\n\nextension ImageStore {\n /// Get the image for the init block from the image store.\n /// If the image does not exist locally, pull the image.\n public func getInitImage(reference: String, auth: Authentication? = nil, progress: ProgressHandler? = nil) async throws -> InitImage {\n do {\n let image = try await self.get(reference: reference)\n return InitImage(image: image)\n } catch let error as ContainerizationError {\n if error.code == .notFound {\n let image = try await self.pull(reference: reference, auth: auth, progress: progress)\n return InitImage(image: image)\n }\n throw error\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Platform.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// Source: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/config.go\n\nimport ContainerizationError\nimport Foundation\n\n/// Platform describes the platform which the image in the manifest runs on.\npublic struct Platform: Sendable, Equatable {\n public static var current: Self {\n var systemInfo = utsname()\n uname(&systemInfo)\n let arch = withUnsafePointer(to: &systemInfo.machine) {\n $0.withMemoryRebound(to: CChar.self, capacity: 1) {\n String(cString: $0)\n }\n }\n switch arch {\n case \"arm64\":\n return .init(arch: \"arm64\", os: \"linux\", variant: \"v8\")\n case \"x86_64\":\n return .init(arch: \"amd64\", os: \"linux\")\n default:\n fatalError(\"unsupported arch \\(arch)\")\n }\n }\n\n /// The computed description, for example, `linux/arm64/v8`.\n public var description: String {\n let architecture = architecture\n if let variant = variant {\n return \"\\(os)/\\(architecture)/\\(variant)\"\n }\n return \"\\(os)/\\(architecture)\"\n }\n\n /// The CPU architecture, for example, `amd64` or `ppc64`.\n public var architecture: String {\n switch _rawArch {\n case \"arm64\", \"arm\", \"aarch64\", \"armhf\", \"armel\":\n return \"arm64\"\n case \"x86_64\", \"x86-64\", \"amd64\":\n return \"amd64\"\n case \"386\", \"ppc64le\", \"i386\", \"s390x\", \"riscv64\":\n return _rawArch\n default:\n return _rawArch\n }\n }\n\n /// The operating system, for example, `linux` or `windows`.\n public var os: String {\n _rawOS\n }\n\n /// An optional field specifying the operating system version, for example on Windows `10.0.14393.1066`.\n public var osVersion: String?\n\n /// An optional field specifying an array of strings, each listing a required OS feature (for example on Windows `win32k`).\n public var osFeatures: [String]?\n\n /// An optional field specifying a variant of the CPU, for example `v7` to specify ARMv7 when architecture is `arm`.\n public var variant: String?\n\n /// The operation system of the image (eg. `linux`).\n private let _rawOS: String\n /// The CPU architecture (eg. `arm64`).\n private let _rawArch: String\n\n public init(arch: String, os: String, osVersion: String? = nil, osFeatures: [String]? = nil, variant: String? = nil) {\n self._rawArch = arch\n self._rawOS = os\n self.osVersion = osVersion\n self.osFeatures = osFeatures\n self.variant = variant\n }\n\n /// Initializes a new platform from a string.\n /// - Parameters:\n /// - platform: A `string` value representing the platform.\n /// ```swift\n /// // Create a new `ImagePlatform` from string.\n /// let platform = try Platform(from: \"linux/amd64\")\n /// ```\n /// ## Throws ##\n /// - Throws: `Error.missingOS` if input is empty\n /// - Throws: `Error.invalidOS` if os is not `linux`\n /// - Throws: `Error.missingArch` if only one `/` is present\n /// - Throws: `Error.invalidArch` if an unrecognized architecture is provided\n /// - Throws: `Error.invalidVariant` if a variant is provided, and it does not apply to the specified architecture\n public init(from platform: String) throws {\n let items = platform.split(separator: \"/\", maxSplits: 1)\n guard let osValue = items.first else {\n throw ContainerizationError(.invalidArgument, message: \"Missing OS in \\(platform)\")\n }\n switch osValue {\n case \"linux\":\n _rawOS = osValue.description\n case \"darwin\":\n _rawOS = osValue.description\n case \"windows\":\n _rawOS = osValue.description\n default:\n throw ContainerizationError(.invalidArgument, message: \"Unknown OS in \\(osValue)\")\n }\n guard items.count > 1 else {\n throw ContainerizationError(.invalidArgument, message: \"Missing architecture in \\(platform)\")\n }\n\n guard let archItems = items.last?.split(separator: \"/\", maxSplits: 1, omittingEmptySubsequences: false) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing architecture in \\(platform)\")\n }\n\n guard let archName = archItems.first else {\n throw ContainerizationError(.invalidArgument, message: \"Missing architecture in \\(platform)\")\n }\n\n switch archName {\n case \"arm\", \"armhf\", \"armel\":\n _rawArch = \"arm\"\n variant = \"v7\"\n case \"aarch64\", \"arm64\":\n variant = \"v8\"\n _rawArch = \"arm64\"\n case \"x86_64\", \"x86-64\", \"amd64\":\n _rawArch = \"amd64\"\n default:\n _rawArch = archName.description\n }\n\n if archItems.count == 2 {\n guard let archVariant = archItems.last else {\n throw ContainerizationError(.invalidArgument, message: \"Missing variant in \\(platform)\")\n }\n\n switch archName {\n case \"arm\":\n switch archVariant {\n case \"v5\", \"v6\", \"v7\", \"v8\":\n variant = archVariant.description\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n case \"armhf\":\n switch archVariant {\n case \"v7\":\n variant = \"v7\"\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n case \"armel\":\n switch archVariant {\n case \"v6\":\n variant = \"v6\"\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n case \"aarch64\", \"arm64\":\n switch archVariant {\n case \"v8\", \"8\":\n variant = \"v8\"\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n case \"x86_64\", \"x86-64\", \"amd64\":\n switch archVariant {\n case \"v1\":\n variant = nil\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n case \"i386\", \"386\", \"ppc64le\", \"riscv64\":\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n }\n }\n\n}\n\nextension Platform: Hashable {\n /**\n `~=` compares two platforms to check if **lhs** platform images are compatible with **rhs** platform\n This operator can be used to check if an image of **lhs** platform can run on **rhs**:\n - `true`: when **rhs**=`arm/v8`, **lhs** is any of `arm/v8`, `arm/v7`, `arm/v6` and `arm/v5`\n - `true`: when **rhs**=`arm/v7`, **lhs** is any of `arm/v7`, `arm/v6` and `arm/v5`\n - `true`: when **rhs**=`arm/v6`, **lhs** is any of `arm/v6` and `arm/v5`\n - `true`: when **rhs**=`amd64`, **lhs** is any of `amd64` and `386`\n - `true`: when **rhs**=**lhs**\n - `false`: otherwise\n - Parameters:\n - lhs: platform whose compatibility is being checked\n - rhs: platform against which compatibility is being checked\n - Returns: `true | false`\n */\n public static func ~= (lhs: Platform, rhs: Platform) -> Bool {\n if lhs.os == rhs.os {\n if lhs._rawArch == rhs._rawArch {\n switch rhs._rawArch {\n case \"arm\":\n guard let lVariant = lhs.variant else {\n return lhs == rhs\n }\n guard let rVariant = rhs.variant else {\n return lhs == rhs\n }\n switch rVariant {\n case \"v8\":\n switch lVariant {\n case \"v5\", \"v6\", \"v7\", \"v8\":\n return true\n default:\n return false\n }\n case \"v7\":\n switch lVariant {\n case \"v5\", \"v6\", \"v7\":\n return true\n default:\n return false\n }\n case \"v6\":\n switch lVariant {\n case \"v5\", \"v6\":\n return true\n default:\n return false\n }\n default:\n return lhs == rhs\n }\n default:\n return lhs == rhs\n }\n }\n if lhs._rawArch == \"386\" && rhs._rawArch == \"amd64\" {\n return true\n }\n }\n return false\n }\n\n /// `==` compares if **lhs** and **rhs** are the exact same platforms.\n public static func == (lhs: Platform, rhs: Platform) -> Bool {\n // NOTE:\n // If the platform struct was created by setting the fields directly and not using (from: String)\n // then, there is a possibility that for arm64 architecture, the variant may be set to nil\n // In that case, the variant should be assumed to v8\n if lhs.architecture == \"arm64\" && rhs.architecture == \"arm64\" {\n // The following checks effectively verify\n // that one operand has nil value and other has \"v8\"\n if lhs.variant == nil || rhs.variant == nil {\n if lhs.variant == \"v8\" || rhs.variant == \"v8\" {\n return true\n }\n }\n }\n\n let osEqual = lhs.os == rhs.os\n let archEqual = lhs.architecture == rhs.architecture\n let variantEqual = lhs.variant == rhs.variant\n\n return osEqual && archEqual && variantEqual\n }\n\n public func hash(into hasher: inout Swift.Hasher) {\n hasher.combine(description)\n }\n}\n\nextension Platform: Codable {\n\n enum CodingKeys: String, CodingKey {\n case os = \"os\"\n case architecture = \"architecture\"\n case variant = \"variant\"\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(os, forKey: .os)\n try container.encode(architecture, forKey: .architecture)\n try container.encodeIfPresent(variant, forKey: .variant)\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let architecture = try container.decodeIfPresent(String.self, forKey: .architecture)\n guard let architecture else {\n throw ContainerizationError(.invalidArgument, message: \"Missing architecture\")\n }\n let os = try container.decodeIfPresent(String.self, forKey: .os)\n guard let os else {\n throw ContainerizationError(.invalidArgument, message: \"Missing OS\")\n }\n let variant = try container.decodeIfPresent(String.self, forKey: .variant)\n self.init(arch: architecture, os: os, variant: variant)\n }\n}\n\npublic func createPlatformMatcher(for platform: Platform?) -> @Sendable (Platform) -> Bool {\n if let platform {\n return { other in\n platform == other\n }\n }\n return { _ in\n true\n }\n}\n\npublic func filterPlatforms(matcher: (Platform) -> Bool, _ descriptors: [Descriptor]) throws -> [Descriptor] {\n var outDescriptors: [Descriptor] = []\n for desc in descriptors {\n guard let p = desc.platform else {\n // pass along descriptor if the platform is not defined\n outDescriptors.append(desc)\n continue\n }\n if matcher(p) {\n outDescriptors.append(desc)\n }\n }\n return outDescriptors\n}\n"], ["/containerization/Sources/ContainerizationNetlink/NetlinkSession.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport ContainerizationOS\nimport Logging\n\n/// `NetlinkSession` facilitates interacting with netlink via a provided `NetlinkSocket`. This is the\n/// core high-level type offered to perform actions to the netlink surface in the kernel.\npublic struct NetlinkSession {\n private static let receiveDataLength = 65536\n private static let mtu: UInt32 = 1280\n private let socket: any NetlinkSocket\n private let log: Logger\n\n /// Creates a new `NetlinkSession`.\n /// - Parameters:\n /// - socket: The `NetlinkSocket` to use for netlink interaction.\n /// - log: The logger to use. The default value is `nil`.\n public init(socket: any NetlinkSocket, log: Logger? = nil) {\n self.socket = socket\n self.log = log ?? Logger(label: \"com.apple.containerization.netlink\")\n }\n\n /// Errors that may occur during netlink interaction.\n public enum Error: Swift.Error, CustomStringConvertible, Equatable {\n case invalidIpAddress\n case invalidPrefixLength\n case unexpectedInfo(type: UInt16)\n case unexpectedOffset(offset: Int, size: Int)\n case unexpectedResidualPackets\n case unexpectedResultSet(count: Int, expected: Int)\n\n /// The description of the errors.\n public var description: String {\n switch self {\n case .invalidIpAddress:\n return \"invalid IP address\"\n case .invalidPrefixLength:\n return \"invalid prefix length\"\n case .unexpectedInfo(let type):\n return \"unexpected response information, type = \\(type)\"\n case .unexpectedOffset(let offset, let size):\n return \"unexpected buffer state, offset = \\(offset), size = \\(size)\"\n case .unexpectedResidualPackets:\n return \"unexpected residual response packets\"\n case .unexpectedResultSet(let count, let expected):\n return \"unexpected result set size, count = \\(count), expected = \\(expected)\"\n }\n }\n }\n\n /// Performs a link set command on an interface.\n /// - Parameters:\n /// - interface: The name of the interface.\n /// - up: The value to set the interface state to.\n public func linkSet(interface: String, up: Bool, mtu: UInt32? = nil) throws {\n // ip link set dev [interface] [up|down]\n let interfaceIndex = try getInterfaceIndex(interface)\n // build the attribute only when mtu is supplied\n let attr: RTAttribute? =\n (mtu != nil)\n ? RTAttribute(\n len: UInt16(RTAttribute.size + MemoryLayout.size),\n type: LinkAttributeType.IFLA_MTU)\n : nil\n let requestSize = NetlinkMessageHeader.size + InterfaceInfo.size + (attr?.paddedLen ?? 0)\n var requestBuffer = [UInt8](repeating: 0, count: requestSize)\n var requestOffset = 0\n\n let requestHeader = NetlinkMessageHeader(\n len: UInt32(requestBuffer.count),\n type: NetlinkType.RTM_NEWLINK,\n flags: NetlinkFlags.NLM_F_REQUEST | NetlinkFlags.NLM_F_ACK,\n pid: socket.pid)\n requestOffset = try requestHeader.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let flags = up ? InterfaceFlags.IFF_UP : 0\n let requestInfo = InterfaceInfo(\n family: UInt8(AddressFamily.AF_PACKET),\n index: interfaceIndex,\n flags: flags,\n change: InterfaceFlags.DEFAULT_CHANGE)\n requestOffset = try requestInfo.appendBuffer(&requestBuffer, offset: requestOffset)\n\n if let attr = attr, let m = mtu {\n requestOffset = try attr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard\n let newRequestOffset =\n requestBuffer.copyIn(as: UInt32.self, value: m, offset: requestOffset)\n else {\n throw NetlinkDataError.sendMarshalFailure\n }\n requestOffset = newRequestOffset\n }\n\n guard requestOffset == requestSize else {\n throw Error.unexpectedOffset(offset: requestOffset, size: requestSize)\n }\n\n try sendRequest(buffer: &requestBuffer)\n let (infos, _) = try parseResponse(infoType: NetlinkType.RTM_NEWLINK) { InterfaceInfo() }\n guard infos.count == 0 else {\n throw Error.unexpectedResultSet(count: infos.count, expected: 0)\n }\n }\n\n /// Performs a link get command on an interface.\n /// Returns information about the interface.\n /// - Parameter interface: The name of the interface to query.\n public func linkGet(interface: String? = nil) throws -> [LinkResponse] {\n // ip link ip show\n let maskAttr = RTAttribute(\n len: UInt16(RTAttribute.size + MemoryLayout.size), type: LinkAttributeType.IFLA_EXT_MASK)\n let interfaceName = try interface.map { try getInterfaceName($0) }\n let interfaceNameAttr = interfaceName.map {\n RTAttribute(len: UInt16(RTAttribute.size + $0.count), type: LinkAttributeType.IFLA_EXT_IFNAME)\n }\n let requestSize =\n NetlinkMessageHeader.size + InterfaceInfo.size + maskAttr.paddedLen + (interfaceNameAttr?.paddedLen ?? 0)\n var requestBuffer = [UInt8](repeating: 0, count: requestSize)\n var requestOffset = 0\n\n let flags =\n interface != nil ? NetlinkFlags.NLM_F_REQUEST : (NetlinkFlags.NLM_F_REQUEST | NetlinkFlags.NLM_F_DUMP)\n let requestHeader = NetlinkMessageHeader(\n len: UInt32(requestBuffer.count),\n type: NetlinkType.RTM_GETLINK,\n flags: flags,\n pid: socket.pid)\n requestOffset = try requestHeader.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let requestInfo = InterfaceInfo(\n family: UInt8(AddressFamily.AF_PACKET),\n index: 0,\n flags: InterfaceFlags.IFF_UP,\n change: InterfaceFlags.DEFAULT_CHANGE)\n requestOffset = try requestInfo.appendBuffer(&requestBuffer, offset: requestOffset)\n\n requestOffset = try maskAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard\n var requestOffset = requestBuffer.copyIn(\n as: UInt32.self,\n value: LinkAttributeMaskFilter.RTEXT_FILTER_VF | LinkAttributeMaskFilter.RTEXT_FILTER_SKIP_STATS,\n offset: requestOffset)\n else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n if let interfaceNameAttr {\n if let interfaceName {\n requestOffset = try interfaceNameAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard let updatedRequestOffset = requestBuffer.copyIn(buffer: interfaceName, offset: requestOffset)\n else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n requestOffset = updatedRequestOffset\n }\n }\n\n guard requestOffset == requestSize else {\n throw Error.unexpectedOffset(offset: requestOffset, size: requestSize)\n }\n\n try sendRequest(buffer: &requestBuffer)\n let (infos, attrDataLists) = try parseResponse(infoType: NetlinkType.RTM_NEWLINK) { InterfaceInfo() }\n var linkResponses: [LinkResponse] = []\n for i in 0...size * ipAddressBytes.count\n let requestSize = NetlinkMessageHeader.size + AddressInfo.size + 2 * addressAttrSize\n var requestBuffer = [UInt8](repeating: 0, count: requestSize)\n var requestOffset = 0\n\n let header = NetlinkMessageHeader(\n len: UInt32(requestBuffer.count),\n type: NetlinkType.RTM_NEWADDR,\n flags: NetlinkFlags.NLM_F_REQUEST | NetlinkFlags.NLM_F_ACK | NetlinkFlags.NLM_F_EXCL\n | NetlinkFlags.NLM_F_CREATE,\n seq: 0,\n pid: socket.pid)\n requestOffset = try header.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let requestInfo = AddressInfo(\n family: UInt8(AddressFamily.AF_INET),\n prefixLength: parsed.prefix,\n flags: 0,\n scope: NetlinkScope.RT_SCOPE_UNIVERSE,\n index: UInt32(interfaceIndex))\n requestOffset = try requestInfo.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let ipLocalAttr = RTAttribute(len: UInt16(addressAttrSize), type: AddressAttributeType.IFA_LOCAL)\n requestOffset = try ipLocalAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard var requestOffset = requestBuffer.copyIn(buffer: ipAddressBytes, offset: requestOffset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n let ipAddressAttr = RTAttribute(len: UInt16(addressAttrSize), type: AddressAttributeType.IFA_ADDRESS)\n requestOffset = try ipAddressAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard let requestOffset = requestBuffer.copyIn(buffer: ipAddressBytes, offset: requestOffset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n guard requestOffset == requestSize else {\n throw Error.unexpectedOffset(offset: requestOffset, size: requestSize)\n }\n\n try sendRequest(buffer: &requestBuffer)\n let (infos, _) = try parseResponse(infoType: NetlinkType.RTM_NEWLINK) { AddressInfo() }\n guard infos.count == 0 else {\n throw Error.unexpectedResultSet(count: infos.count, expected: 0)\n }\n }\n\n private func parseCIDR(cidr: String) throws -> (address: String, prefix: UInt8) {\n let split = cidr.components(separatedBy: \"/\")\n guard split.count == 2 else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n let address = split[0]\n guard let prefixLength = PrefixLength(split[1]) else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n guard prefixLength >= 0 && prefixLength <= 32 else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n return (address, prefixLength)\n }\n\n /// Adds a route to an interface.\n /// - Parameters:\n /// - interface: The name of the interface.\n /// - destinationAddress: The destination address to route to.\n /// - srcAddr: The source address to route from.\n public func routeAdd(\n interface: String,\n destinationAddress: String,\n srcAddr: String\n ) throws {\n // ip route add [dest-cidr] dev [interface] src [src-addr] proto kernel\n let parsed = try parseCIDR(cidr: destinationAddress)\n let interfaceIndex = try getInterfaceIndex(interface)\n let dstAddrBytes = try IPv4Address(parsed.address).networkBytes\n let dstAddrAttrSize = RTAttribute.size + dstAddrBytes.count\n let srcAddrBytes = try IPv4Address(srcAddr).networkBytes\n let srcAddrAttrSize = RTAttribute.size + srcAddrBytes.count\n let interfaceAttrSize = RTAttribute.size + MemoryLayout.size\n let requestSize =\n NetlinkMessageHeader.size + RouteInfo.size + dstAddrAttrSize + srcAddrAttrSize + interfaceAttrSize\n var requestBuffer = [UInt8](repeating: 0, count: requestSize)\n var requestOffset = 0\n\n let header = NetlinkMessageHeader(\n len: UInt32(requestBuffer.count),\n type: NetlinkType.RTM_NEWROUTE,\n flags: NetlinkFlags.NLM_F_REQUEST | NetlinkFlags.NLM_F_ACK | NetlinkFlags.NLM_F_EXCL\n | NetlinkFlags.NLM_F_CREATE,\n pid: socket.pid)\n requestOffset = try header.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let requestInfo = RouteInfo(\n family: UInt8(AddressFamily.AF_INET),\n dstLen: parsed.prefix,\n srcLen: 0,\n tos: 0,\n table: RouteTable.MAIN,\n proto: RouteProtocol.KERNEL,\n scope: RouteScope.LINK,\n type: RouteType.UNICAST,\n flags: 0)\n requestOffset = try requestInfo.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let dstAddrAttr = RTAttribute(len: UInt16(dstAddrAttrSize), type: RouteAttributeType.DST)\n requestOffset = try dstAddrAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard var requestOffset = requestBuffer.copyIn(buffer: dstAddrBytes, offset: requestOffset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n let srcAddrAttr = RTAttribute(len: UInt16(dstAddrAttrSize), type: RouteAttributeType.PREFSRC)\n requestOffset = try srcAddrAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard var requestOffset = requestBuffer.copyIn(buffer: srcAddrBytes, offset: requestOffset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n let interfaceAttr = RTAttribute(len: UInt16(interfaceAttrSize), type: RouteAttributeType.OIF)\n requestOffset = try interfaceAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard\n let requestOffset = requestBuffer.copyIn(\n as: UInt32.self,\n value: UInt32(interfaceIndex),\n offset: requestOffset)\n else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n guard requestOffset == requestSize else {\n throw Error.unexpectedOffset(offset: requestOffset, size: requestSize)\n }\n\n try sendRequest(buffer: &requestBuffer)\n let (infos, _) = try parseResponse(infoType: NetlinkType.RTM_NEWLINK) { AddressInfo() }\n guard infos.count == 0 else {\n throw Error.unexpectedResultSet(count: infos.count, expected: 0)\n }\n }\n\n /// Adds a default route to an interface.\n /// - Parameters:\n /// - interface: The name of the interface.\n /// - gateway: The gateway address.\n public func routeAddDefault(\n interface: String,\n gateway: String\n ) throws {\n // ip route add default via [dst-address] src [src-address]\n let dstAddrBytes = try IPv4Address(gateway).networkBytes\n let dstAddrAttrSize = RTAttribute.size + dstAddrBytes.count\n\n let interfaceAttrSize = RTAttribute.size + MemoryLayout.size\n let interfaceIndex = try getInterfaceIndex(interface)\n let requestSize = NetlinkMessageHeader.size + RouteInfo.size + dstAddrAttrSize + interfaceAttrSize\n\n var requestBuffer = [UInt8](repeating: 0, count: requestSize)\n var requestOffset = 0\n\n let header = NetlinkMessageHeader(\n len: UInt32(requestBuffer.count),\n type: NetlinkType.RTM_NEWROUTE,\n flags: NetlinkFlags.NLM_F_REQUEST | NetlinkFlags.NLM_F_ACK | NetlinkFlags.NLM_F_EXCL\n | NetlinkFlags.NLM_F_CREATE,\n pid: socket.pid)\n requestOffset = try header.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let requestInfo = RouteInfo(\n family: UInt8(AddressFamily.AF_INET),\n dstLen: 0,\n srcLen: 0,\n tos: 0,\n table: RouteTable.MAIN,\n proto: RouteProtocol.BOOT,\n scope: RouteScope.UNIVERSE,\n type: RouteType.UNICAST,\n flags: 0)\n requestOffset = try requestInfo.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let dstAddrAttr = RTAttribute(len: UInt16(dstAddrAttrSize), type: RouteAttributeType.GATEWAY)\n requestOffset = try dstAddrAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard var requestOffset = requestBuffer.copyIn(buffer: dstAddrBytes, offset: requestOffset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n let interfaceAttr = RTAttribute(len: UInt16(interfaceAttrSize), type: RouteAttributeType.OIF)\n requestOffset = try interfaceAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard\n let requestOffset = requestBuffer.copyIn(\n as: UInt32.self,\n value: UInt32(interfaceIndex),\n offset: requestOffset)\n else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n guard requestOffset == requestSize else {\n throw Error.unexpectedOffset(offset: requestOffset, size: requestSize)\n }\n\n try sendRequest(buffer: &requestBuffer)\n let (infos, _) = try parseResponse(infoType: NetlinkType.RTM_NEWLINK) { AddressInfo() }\n guard infos.count == 0 else {\n throw Error.unexpectedResultSet(count: infos.count, expected: 0)\n }\n }\n\n private func getInterfaceName(_ interface: String) throws -> [UInt8] {\n guard let interfaceNameData = interface.data(using: .utf8) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n var interfaceName = [UInt8](interfaceNameData)\n interfaceName.append(0)\n\n while interfaceName.count % MemoryLayout.size != 0 {\n interfaceName.append(0)\n }\n\n return interfaceName\n }\n\n private func getInterfaceIndex(_ interface: String) throws -> Int32 {\n let linkResponses = try linkGet(interface: interface)\n guard linkResponses.count == 1 else {\n throw Error.unexpectedResultSet(count: linkResponses.count, expected: 1)\n }\n\n return linkResponses[0].interfaceIndex\n }\n\n private func sendRequest(buffer: inout [UInt8]) throws {\n log.trace(\"SEND-LENGTH: \\(buffer.count)\")\n log.trace(\"SEND-DUMP: \\(buffer[0.. ([UInt8], Int) {\n var buffer = [UInt8](repeating: 0, count: Self.receiveDataLength)\n let size = try socket.recv(buf: &buffer, len: Self.receiveDataLength, flags: 0)\n log.trace(\"RECV-LENGTH: \\(size)\")\n log.trace(\"RECV-DUMP: \\(buffer[0..(infoType: UInt16? = nil, _ infoProvider: () -> T) throws -> (\n [T], [[RTAttributeData]]\n ) {\n var infos: [T] = []\n var attrDataLists: [[RTAttributeData]] = []\n\n var moreResponses = false\n repeat {\n var (buffer, size) = try receiveResponse()\n let header: NetlinkMessageHeader\n var offset = 0\n\n (header, offset) = try parseHeader(buffer: &buffer, offset: offset)\n if let infoType {\n if header.type == infoType {\n log.trace(\n \"RECV-INFO-DUMP: dump = \\(buffer[offset.. (Int32, Int) {\n guard let errorPtr = buffer.bind(as: Int32.self, offset: offset) else {\n throw NetlinkDataError.recvUnmarshalFailure\n }\n\n let rc = errorPtr.pointee\n log.trace(\"RECV-ERR-CODE: \\(rc)\")\n\n return (rc, offset + MemoryLayout.size)\n }\n\n private func parseErrorResponse(buffer: inout [UInt8], offset: Int) throws -> Int {\n var (rc, offset) = try parseErrorCode(buffer: &buffer, offset: offset)\n log.trace(\n \"RECV-ERR-HEADER-DUMP: dump = \\(buffer[offset.. (NetlinkMessageHeader, Int) {\n log.trace(\"RECV-HEADER-DUMP: dump = \\(buffer[offset.. (\n [RTAttributeData], Int\n ) {\n var attrDatas: [RTAttributeData] = []\n var offset = offset\n var residualCount = residualCount\n log.trace(\"RECV-RESIDUAL: \\(residualCount)\")\n\n while residualCount > 0 {\n var attr = RTAttribute()\n log.trace(\" RECV-ATTR-DUMP: dump = \\(buffer[offset..= 0 {\n log.trace(\" RECV-ATTR-DATA-DUMP: dump = \\(buffer[offset.. Kernel {\n let manifest = try await image.manifest(for: platform.ociPlatform())\n guard let descriptor = manifest.layers.first, descriptor.mediaType == Self.mediaType else {\n throw ContainerizationError(.notFound, message: \"kernel descriptor for \\(platform) not found\")\n }\n let content = try await image.getContent(digest: descriptor.digest)\n return Kernel(\n path: content.path,\n platform: platform\n )\n }\n\n /// Create a new kernel image with the reference as the name.\n /// This will create a multi arch image containing kernel's for each provided architecture.\n public static func create(reference: String, binaries: [Kernel], labels: [String: String] = [:], imageStore: ImageStore, contentStore: ContentStore) async throws -> KernelImage\n {\n let indexDescriptorStore = AsyncStore()\n try await contentStore.ingest { ingestPath in\n var descriptors = [Descriptor]()\n let writer = try ContentWriter(for: ingestPath)\n\n for kernel in binaries {\n var result = try writer.create(from: kernel.path)\n let platform = kernel.platform.ociPlatform()\n let layerDescriptor = Descriptor(\n mediaType: mediaType,\n digest: result.digest.digestString,\n size: result.size,\n platform: platform)\n let rootfsConfig = ContainerizationOCI.Rootfs(type: \"layers\", diffIDs: [result.digest.digestString])\n let runtimeConfig = ContainerizationOCI.ImageConfig(labels: labels)\n let imageConfig = ContainerizationOCI.Image(architecture: platform.architecture, os: platform.os, config: runtimeConfig, rootfs: rootfsConfig)\n\n result = try writer.create(from: imageConfig)\n let configDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.imageConfig, digest: result.digest.digestString, size: result.size)\n\n let manifest = Manifest(config: configDescriptor, layers: [layerDescriptor])\n result = try writer.create(from: manifest)\n let manifestDescriptor = Descriptor(\n mediaType: ContainerizationOCI.MediaTypes.imageManifest, digest: result.digest.digestString, size: result.size, platform: platform)\n descriptors.append(manifestDescriptor)\n }\n let index = ContainerizationOCI.Index(manifests: descriptors)\n let result = try writer.create(from: index)\n let indexDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.index, digest: result.digest.digestString, size: result.size)\n await indexDescriptorStore.set(indexDescriptor)\n }\n\n guard let indexDescriptor = await indexDescriptorStore.get() else {\n throw ContainerizationError(.notFound, message: \"image for \\(reference) not found\")\n }\n\n let description = Image.Description(reference: reference, descriptor: indexDescriptor)\n let image = try await imageStore.create(description: description)\n return KernelImage(image: image)\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/LocalOCILayoutClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport Crypto\nimport Foundation\nimport NIOCore\nimport NIOFoundationCompat\n\npackage final class LocalOCILayoutClient: ContentClient {\n let cs: LocalContentStore\n\n package init(root: URL) throws {\n self.cs = try LocalContentStore(path: root)\n }\n\n private func _fetch(digest: String) async throws -> Content {\n guard let c: Content = try await self.cs.get(digest: digest) else {\n throw Error.missingContent(digest)\n }\n return c\n }\n\n package func fetch(name: String, descriptor: Descriptor) async throws -> T {\n let c = try await self._fetch(digest: descriptor.digest)\n return try c.decode()\n }\n\n package func fetchBlob(name: String, descriptor: Descriptor, into file: URL, progress: ProgressHandler?) async throws -> (Int64, SHA256Digest) {\n let c = try await self._fetch(digest: descriptor.digest)\n let fileManager = FileManager.default\n let filePath = file.absolutePath()\n if !fileManager.fileExists(atPath: filePath) {\n let src = c.path\n try fileManager.copyItem(at: src, to: file)\n\n if let progress, let fileSize = fileManager.fileSize(atPath: filePath) {\n await progress([\n ProgressEvent(event: \"add-size\", value: fileSize)\n ])\n }\n }\n let size = try Int64(c.size())\n let digest = try c.digest()\n return (size, digest)\n }\n\n package func fetchData(name: String, descriptor: Descriptor) async throws -> Data {\n let c = try await self._fetch(digest: descriptor.digest)\n return try c.data()\n }\n\n package func push(\n name: String,\n ref: String,\n descriptor: Descriptor,\n streamGenerator: () throws -> T,\n progress: ProgressHandler?\n ) async throws where T.Element == ByteBuffer {\n let input = try streamGenerator()\n\n let (id, dir) = try await self.cs.newIngestSession()\n do {\n let into = dir.appendingPathComponent(descriptor.digest.trimmingDigestPrefix)\n guard FileManager.default.createFile(atPath: into.path, contents: nil) else {\n throw Error.cannotCreateFile\n }\n let fd = try FileHandle(forWritingTo: into)\n defer {\n try? fd.close()\n }\n var wrote = 0\n var hasher = SHA256()\n\n for try await buffer in input {\n wrote += buffer.readableBytes\n try fd.write(contentsOf: buffer.readableBytesView)\n hasher.update(data: buffer.readableBytesView)\n }\n try await self.cs.completeIngestSession(id)\n } catch {\n try await self.cs.cancelIngestSession(id)\n }\n }\n}\n\nextension LocalOCILayoutClient {\n private static let ociLayoutFileName = \"oci-layout\"\n private static let ociLayoutVersionString = \"imageLayoutVersion\"\n private static let ociLayoutIndexFileName = \"index.json\"\n\n package func loadIndexFromOCILayout(directory: URL) throws -> ContainerizationOCI.Index {\n let fm = FileManager.default\n let decoder = JSONDecoder()\n\n let ociLayoutFile = directory.appendingPathComponent(Self.ociLayoutFileName)\n guard fm.fileExists(atPath: ociLayoutFile.absolutePath()) else {\n throw ContainerizationError(.notFound, message: ociLayoutFile.absolutePath())\n }\n var data = try Data(contentsOf: ociLayoutFile)\n let ociLayout = try decoder.decode([String: String].self, from: data)\n guard ociLayout[Self.ociLayoutVersionString] != nil else {\n throw ContainerizationError(.empty, message: \"missing key \\(Self.ociLayoutVersionString) in \\(ociLayoutFile.absolutePath())\")\n }\n\n let indexFile = directory.appendingPathComponent(Self.ociLayoutIndexFileName)\n guard fm.fileExists(atPath: indexFile.absolutePath()) else {\n throw ContainerizationError(.notFound, message: indexFile.absolutePath())\n }\n data = try Data(contentsOf: indexFile)\n let index = try decoder.decode(ContainerizationOCI.Index.self, from: data)\n return index\n }\n\n package func createOCILayoutStructure(directory: URL, manifests: [Descriptor]) throws {\n let fm = FileManager.default\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.withoutEscapingSlashes]\n\n let ingestDir = directory.appendingPathComponent(\"ingest\")\n try? fm.removeItem(at: ingestDir)\n let ociLayoutContent: [String: String] = [\n Self.ociLayoutVersionString: \"1.0.0\"\n ]\n\n var data = try encoder.encode(ociLayoutContent)\n var p = directory.appendingPathComponent(Self.ociLayoutFileName).absolutePath()\n guard fm.createFile(atPath: p, contents: data) else {\n throw ContainerizationError(.internalError, message: \"failed to create file \\(p)\")\n }\n let idx = ContainerizationOCI.Index(schemaVersion: 2, manifests: manifests)\n data = try encoder.encode(idx)\n p = directory.appendingPathComponent(Self.ociLayoutIndexFileName).absolutePath()\n guard fm.createFile(atPath: p, contents: data) else {\n throw ContainerizationError(.internalError, message: \"failed to create file \\(p)\")\n }\n }\n\n package func setImageReferenceAnnotation(descriptor: inout Descriptor, reference: String) {\n var annotations = descriptor.annotations ?? [:]\n annotations[AnnotationKeys.containerizationImageName] = reference\n annotations[AnnotationKeys.containerdImageName] = reference\n annotations[AnnotationKeys.openContainersImageName] = reference\n descriptor.annotations = annotations\n }\n\n package func getImageReferencefromDescriptor(descriptor: Descriptor) -> String? {\n let annotations = descriptor.annotations\n guard let annotations else {\n return nil\n }\n\n // Annotations here do not conform to the OCI image specification.\n // The interpretation of the annotations \"org.opencontainers.image.ref.name\" and\n // \"io.containerd.image.name\" is under debate:\n // - OCI spec examples suggest it should be the image tag:\n // https://github.com/opencontainers/image-spec/blob/fbb4662eb53b80bd38f7597406cf1211317768f0/image-layout.md?plain=1#L175\n // - Buildkitd maintainers argue it should represent the full image name:\n // https://github.com/moby/buildkit/issues/4615#issuecomment-2521810830\n // Until a consensus is reached, the preference is given to \"com.apple.containerization.image.name\" and then to\n // using \"io.containerd.image.name\" as it is the next safest choice\n if let name = annotations[AnnotationKeys.containerizationImageName] {\n return name\n }\n if let name = annotations[AnnotationKeys.containerdImageName] {\n return name\n }\n if let name = annotations[AnnotationKeys.openContainersImageName] {\n return name\n }\n return nil\n }\n\n package enum Error: Swift.Error {\n case missingContent(_ digest: String)\n case unsupportedInput\n case cannotCreateFile\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/RegistryClient+Push.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport NIO\n\nextension RegistryClient {\n /// Pushes the content specified by a descriptor to a remote registry.\n /// - Parameters:\n /// - name: The namespace which the descriptor should belong under.\n /// - tag: The tag or digest for uniquely identifying the manifest.\n /// By convention, any portion that may be a partial or whole digest\n /// will be proceeded by an `@`. Anything preceding the `@` will be referred\n /// to as \"tag\".\n /// This is usually broken down into the following possibilities:\n /// 1. \n /// 2. @\n /// 3. @\n /// The tag is anything except `@` and `:`, and digest is anything after the `@`\n /// - descriptor: The OCI descriptor of the content to be pushed.\n /// - streamGenerator: A closure that produces an`AsyncStream` of `ByteBuffer`\n /// for streaming data to the `HTTPClientRequest.Body`.\n /// The caller is responsible for providing the `AsyncStream` where the data may come from\n /// a file on disk, data in memory, etc.\n /// - progress: The progress handler to invoke as data is sent.\n public func push(\n name: String,\n ref tag: String,\n descriptor: Descriptor,\n streamGenerator: () throws -> T,\n progress: ProgressHandler?\n ) async throws where T.Element == ByteBuffer {\n var components = base\n\n let mediaType = descriptor.mediaType\n if mediaType.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Missing media type for descriptor \\(descriptor.digest)\")\n }\n\n var isManifest = false\n var existCheck: [String] = []\n\n switch mediaType {\n case MediaTypes.dockerManifest, MediaTypes.dockerManifestList, MediaTypes.imageManifest, MediaTypes.index:\n isManifest = true\n existCheck = self.getManifestPath(tag: tag, digest: descriptor.digest)\n default:\n existCheck = [\"blobs\", descriptor.digest]\n }\n\n // Check if the content already exists.\n components.path = \"/v2/\\(name)/\\(existCheck.joined(separator: \"/\"))\"\n\n let mediaTypes = [\n mediaType,\n \"*/*\",\n ]\n\n var headers = [\n (\"Accept\", mediaTypes.joined(separator: \", \"))\n ]\n\n try await request(components: components, method: .HEAD, headers: headers) { response in\n if response.status == .ok {\n var exists = false\n if isManifest && existCheck[1] != descriptor.digest {\n if descriptor.digest == response.headers.first(name: \"Docker-Content-Digest\") {\n exists = true\n }\n } else {\n exists = true\n }\n\n if exists {\n throw ContainerizationError(.exists, message: \"Content already exists \\(descriptor.digest)\")\n }\n } else if response.status != .notFound {\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n }\n\n if isManifest {\n let path = self.getManifestPath(tag: tag, digest: descriptor.digest)\n components.path = \"/v2/\\(name)/\\(path.joined(separator: \"/\"))\"\n headers = [\n (\"Content-Type\", mediaType)\n ]\n } else {\n // Start upload request for blobs.\n components.path = \"/v2/\\(name)/blobs/uploads/\"\n try await request(components: components, method: .POST) { response in\n switch response.status {\n case .ok, .accepted, .noContent:\n break\n case .created:\n throw ContainerizationError(.exists, message: \"Content already exists \\(descriptor.digest)\")\n default:\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n\n // Get the location to upload the blob.\n guard let location = response.headers.first(name: \"Location\") else {\n throw ContainerizationError(.invalidArgument, message: \"Missing required header Location\")\n }\n\n guard let urlComponents = URLComponents(string: location) else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid url \\(location)\")\n }\n var queryItems = urlComponents.queryItems ?? []\n queryItems.append(URLQueryItem(name: \"digest\", value: descriptor.digest))\n components.path = urlComponents.path\n components.queryItems = queryItems\n headers = [\n (\"Content-Type\", \"application/octet-stream\"),\n (\"Content-Length\", String(descriptor.size)),\n ]\n }\n }\n\n // We have to pass a body closure rather than a body to reset the stream when retrying.\n let bodyClosure = {\n let stream = try streamGenerator()\n let body = HTTPClientRequest.Body.stream(stream, length: .known(descriptor.size))\n return body\n }\n\n return try await request(components: components, method: .PUT, bodyClosure: bodyClosure, headers: headers) { response in\n switch response.status {\n case .ok, .created, .noContent:\n break\n default:\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n\n guard descriptor.digest == response.headers.first(name: \"Docker-Content-Digest\") else {\n let required = response.headers.first(name: \"Docker-Content-Digest\") ?? \"\"\n throw ContainerizationError(.internalError, message: \"Digest mismatch \\(descriptor.digest) != \\(required)\")\n }\n }\n }\n\n private func getManifestPath(tag: String, digest: String) -> [String] {\n var object = tag\n if let i = tag.firstIndex(of: \"@\") {\n let index = tag.index(after: i)\n if String(tag[index...]) != digest {\n object = \"\"\n } else {\n object = String(tag[...i])\n }\n }\n\n if object == \"\" {\n return [\"manifests\", digest]\n }\n\n return [\"manifests\", object]\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/ManagedContainer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nactor ManagedContainer {\n let id: String\n let initProcess: ManagedProcess\n\n private let _log: Logger\n private let _bundle: ContainerizationOCI.Bundle\n private var _execs: [String: ManagedProcess] = [:]\n\n var pid: Int32 {\n self.initProcess.pid\n }\n\n init(\n id: String,\n stdio: HostStdio,\n spec: ContainerizationOCI.Spec,\n log: Logger\n ) throws {\n let bundle = try ContainerizationOCI.Bundle.create(\n path: Self.craftBundlePath(id: id),\n spec: spec\n )\n log.info(\"created bundle with spec \\(spec)\")\n\n let initProcess = try ManagedProcess(\n id: id,\n stdio: stdio,\n bundle: bundle,\n owningPid: nil,\n log: log\n )\n log.info(\"created managed init process\")\n\n self.initProcess = initProcess\n self.id = id\n self._bundle = bundle\n self._log = log\n }\n}\n\nextension ManagedContainer {\n private func ensureExecExists(_ id: String) throws {\n if self._execs[id] == nil {\n throw ContainerizationError(\n .invalidState,\n message: \"exec \\(id) does not exist in container \\(self.id)\"\n )\n }\n }\n\n func createExec(\n id: String,\n stdio: HostStdio,\n process: ContainerizationOCI.Process\n ) throws {\n // Write the process config to the bundle, and pass this on\n // over to ManagedProcess to deal with.\n try self._bundle.createExecSpec(\n id: id,\n process: process\n )\n let process = try ManagedProcess(\n id: id,\n stdio: stdio,\n bundle: self._bundle,\n owningPid: self.initProcess.pid,\n log: self._log\n )\n self._execs[id] = process\n }\n\n func start(execID: String) async throws -> Int32 {\n let proc = try self.getExecOrInit(execID: execID)\n return try await ProcessSupervisor.default.start(process: proc)\n }\n\n func wait(execID: String) async throws -> Int32 {\n let proc = try self.getExecOrInit(execID: execID)\n return await proc.wait()\n }\n\n func kill(execID: String, _ signal: Int32) throws {\n let proc = try self.getExecOrInit(execID: execID)\n try proc.kill(signal)\n }\n\n func resize(execID: String, size: Terminal.Size) throws {\n let proc = try self.getExecOrInit(execID: execID)\n try proc.resize(size: size)\n }\n\n func closeStdin(execID: String) throws {\n let proc = try self.getExecOrInit(execID: execID)\n try proc.closeStdin()\n }\n\n func deleteExec(id: String) throws {\n try ensureExecExists(id)\n do {\n try self._bundle.deleteExecSpec(id: id)\n } catch {\n self._log.error(\"failed to remove exec spec from filesystem: \\(error)\")\n }\n self._execs.removeValue(forKey: id)\n }\n\n func delete() throws {\n try self._bundle.delete()\n }\n\n func getExecOrInit(execID: String) throws -> ManagedProcess {\n if execID == self.id {\n return self.initProcess\n }\n guard let proc = self._execs[execID] else {\n throw ContainerizationError(\n .invalidState,\n message: \"exec \\(execID) does not exist in container \\(self.id)\"\n )\n }\n return proc\n }\n}\n\nextension ContainerizationOCI.Bundle {\n func createExecSpec(id: String, process: ContainerizationOCI.Process) throws {\n let specDir = self.path.appending(path: \"execs/\\(id)\")\n\n let fm = FileManager.default\n try fm.createDirectory(\n atPath: specDir.path,\n withIntermediateDirectories: true\n )\n\n let specData = try JSONEncoder().encode(process)\n let processConfigPath = specDir.appending(path: \"process.json\")\n try specData.write(to: processConfigPath)\n }\n\n func getExecSpecPath(id: String) -> URL {\n self.path.appending(path: \"execs/\\(id)/process.json\")\n }\n\n func deleteExecSpec(id: String) throws {\n let specDir = self.path.appending(path: \"execs/\\(id)\")\n\n let fm = FileManager.default\n try fm.removeItem(at: specDir)\n }\n}\n\nextension ManagedContainer {\n static func craftBundlePath(id: String) -> URL {\n URL(fileURLWithPath: \"/run/container\").appending(path: id)\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4Reader+Export.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationArchive\nimport Foundation\nimport SystemPackage\n\nextension EXT4.EXT4Reader {\n public func export(archive: FilePath) throws {\n let config = ArchiveWriterConfiguration(\n format: .paxRestricted, filter: .none, options: [Options.xattrformat(.schily)])\n let writer = try ArchiveWriter(configuration: config)\n try writer.open(file: archive.url)\n var items = self.tree.root.pointee.children\n let hardlinkedInodes = Set(self.hardlinks.values)\n var hardlinkTargets: [EXT4.InodeNumber: FilePath] = [:]\n\n while items.count > 0 {\n let itemPtr = items.removeFirst()\n let item = itemPtr.pointee\n let inode = try self.getInode(number: item.inode)\n let entry = WriteEntry()\n let mode = inode.mode\n let size: UInt64 = (UInt64(inode.sizeHigh) << 32) | UInt64(inode.sizeLow)\n entry.permissions = mode\n guard let path = item.path else {\n continue\n }\n if hardlinkedInodes.contains(item.inode) {\n hardlinkTargets[item.inode] = path\n }\n guard self.hardlinks[path] == nil else {\n continue\n }\n var attributes: [EXT4.ExtendedAttribute] = []\n let buffer: [UInt8] = EXT4.tupleToArray(inode.inlineXattrs)\n if !buffer.allZeros {\n try attributes.append(contentsOf: Self.readInlineExtendedAttributes(from: buffer))\n }\n if inode.xattrBlockLow != 0 {\n let block = inode.xattrBlockLow\n try self.seek(block: block)\n guard let buffer = try self.handle.read(upToCount: Int(self.blockSize)) else {\n throw EXT4.Error.couldNotReadBlock(block)\n }\n try attributes.append(contentsOf: Self.readBlockExtendedAttributes(from: [UInt8](buffer)))\n }\n\n var xattrs: [String: Data] = [:]\n for attribute in attributes {\n guard attribute.fullName != \"system.data\" else {\n continue\n }\n xattrs[attribute.fullName] = Data(attribute.value)\n }\n\n let pathStr = path.description\n entry.path = pathStr\n entry.size = Int64(size)\n entry.group = gid_t(inode.gid)\n entry.owner = uid_t(inode.uid)\n entry.creationDate = Date(fsTimestamp: UInt64((inode.ctimeExtra << 32) | inode.ctime))\n entry.modificationDate = Date(fsTimestamp: UInt64((inode.mtimeExtra << 32) | inode.mtime))\n entry.contentAccessDate = Date(fsTimestamp: UInt64((inode.atimeExtra << 32) | inode.atime))\n entry.xattrs = xattrs\n\n if mode.isDir() {\n entry.fileType = .directory\n for child in item.children {\n items.append(child)\n }\n if pathStr == \"\" {\n continue\n }\n try writer.writeEntry(entry: entry, data: nil)\n } else if mode.isReg() {\n entry.fileType = .regular\n var data = Data()\n var remaining: UInt64 = size\n if let block = item.blocks {\n for dataBlock in block.start.. self.blockSize {\n count = self.blockSize\n } else {\n count = remaining\n }\n guard let dataBytes = try self.handle.read(upToCount: Int(count)) else {\n throw EXT4.Error.couldNotReadBlock(dataBlock)\n }\n data.append(dataBytes)\n remaining -= UInt64(dataBytes.count)\n }\n }\n if let additionalBlocks = item.additionalBlocks {\n for block in additionalBlocks {\n for dataBlock in block.start.. self.blockSize {\n count = self.blockSize\n } else {\n count = remaining\n }\n guard let dataBytes = try self.handle.read(upToCount: Int(count)) else {\n throw EXT4.Error.couldNotReadBlock(dataBlock)\n }\n data.append(dataBytes)\n remaining -= UInt64(dataBytes.count)\n }\n }\n }\n try writer.writeEntry(entry: entry, data: data)\n } else if mode.isLink() {\n entry.fileType = .symbolicLink\n if size < 60 {\n let linkBytes = EXT4.tupleToArray(inode.block)\n entry.symlinkTarget = String(bytes: linkBytes, encoding: .utf8) ?? \"\"\n } else {\n if let block = item.blocks {\n try self.seek(block: block.start)\n guard let linkBytes = try self.handle.read(upToCount: Int(size)) else {\n throw EXT4.Error.couldNotReadBlock(block.start)\n }\n entry.symlinkTarget = String(bytes: linkBytes, encoding: .utf8) ?? \"\"\n }\n }\n try writer.writeEntry(entry: entry, data: nil)\n } else { // do not process sockets, fifo, character and block devices\n continue\n }\n }\n for (path, number) in self.hardlinks {\n guard let targetPath = hardlinkTargets[number] else {\n continue\n }\n let inode = try self.getInode(number: number)\n let entry = WriteEntry()\n entry.path = path.description\n entry.hardlink = targetPath.description\n entry.permissions = inode.mode\n entry.group = gid_t(inode.gid)\n entry.owner = uid_t(inode.uid)\n entry.creationDate = Date(fsTimestamp: UInt64((inode.ctimeExtra << 32) | inode.ctime))\n entry.modificationDate = Date(fsTimestamp: UInt64((inode.mtimeExtra << 32) | inode.mtime))\n entry.contentAccessDate = Date(fsTimestamp: UInt64((inode.atimeExtra << 32) | inode.atime))\n try writer.writeEntry(entry: entry, data: nil)\n }\n try writer.finishEncoding()\n }\n\n @available(*, deprecated, renamed: \"readInlineExtendedAttributes(from:)\")\n public static func readInlineExtenedAttributes(from buffer: [UInt8]) throws -> [EXT4.ExtendedAttribute] {\n try readInlineExtendedAttributes(from: buffer)\n }\n\n public static func readInlineExtendedAttributes(from buffer: [UInt8]) throws -> [EXT4.ExtendedAttribute] {\n let header = UInt32(littleEndian: buffer[0...4].withUnsafeBytes { $0.load(as: UInt32.self) })\n if header != EXT4.XAttrHeaderMagic {\n throw EXT4.FileXattrsState.Error.missingXAttrHeader\n }\n return try EXT4.FileXattrsState.read(buffer: buffer, start: 4, offset: 4)\n }\n\n @available(*, deprecated, renamed: \"readBlockExtendedAttributes(from:)\")\n public static func readBlockExtenedAttributes(from buffer: [UInt8]) throws -> [EXT4.ExtendedAttribute] {\n try readBlockExtendedAttributes(from: buffer)\n }\n\n public static func readBlockExtendedAttributes(from buffer: [UInt8]) throws -> [EXT4.ExtendedAttribute] {\n let header = UInt32(littleEndian: buffer[0...4].withUnsafeBytes { $0.load(as: UInt32.self) })\n if header != EXT4.XAttrHeaderMagic {\n throw EXT4.FileXattrsState.Error.missingXAttrHeader\n }\n\n return try EXT4.FileXattrsState.read(buffer: [UInt8](buffer), start: 32, offset: 0)\n }\n\n func seek(block: UInt32) throws {\n try self.handle.seek(toOffset: UInt64(block) * blockSize)\n }\n}\n\nextension Date {\n init(fsTimestamp: UInt64) {\n if fsTimestamp == 0 {\n self = Date.distantPast\n return\n }\n\n let seconds = Int64(fsTimestamp & 0x3_ffff_ffff)\n let nanoseconds = Double(fsTimestamp >> 34) / 1_000_000_000\n\n self = Date(timeIntervalSince1970: Double(seconds) + nanoseconds)\n }\n}\n#endif\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Xattrs.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/*\n * Note: Both the entries and values for the attributes need to occupy a size that is a multiple of 4,\n * meaning, in cases where the attribute name or value is less than not a multiple of 4, it is padded with 0\n * until it reaches that size.\n */\n\nextension EXT4 {\n public struct ExtendedAttribute {\n public static let prefixMap: [Int: String] = [\n 1: \"user.\",\n 2: \"system.posix_acl_access\",\n 3: \"system.posix_acl_default\",\n 4: \"trusted.\",\n 6: \"security.\",\n 7: \"system.\",\n 8: \"system.richacl\",\n ]\n\n let name: String\n let index: UInt8\n let value: [UInt8]\n\n var sizeValue: UInt32 {\n UInt32((value.count + 3) & ~3)\n }\n\n var sizeEntry: UInt32 {\n UInt32((name.count + 3) & ~3 + 16) // 16 bytes are needed to store other metadata for the xattr entry\n }\n\n var size: UInt32 {\n sizeEntry + sizeValue\n }\n\n var fullName: String {\n Self.decompressName(id: Int(index), suffix: name)\n }\n\n var hash: UInt32 {\n var hash: UInt32 = 0\n for char in name {\n hash = (hash << 5) ^ (hash >> 27) ^ UInt32(char.asciiValue!)\n }\n var i = 0\n while i + 3 < value.count {\n let s = value[i..> 16) ^ v\n i += 4\n }\n if value.count % 4 != 0 {\n let last = value.count & ~3\n var buff: [UInt8] = [0, 0, 0, 0]\n for (i, byte) in value[last...].enumerated() {\n buff[i] = byte\n }\n let v = UInt32(littleEndian: buff.withUnsafeBytes { $0.load(as: UInt32.self) })\n hash = (hash << 16) ^ (hash >> 16) ^ v\n }\n return hash\n }\n\n init(name: String, value: [UInt8]) {\n let compressed = Self.compressName(name)\n self.name = compressed.str\n self.index = compressed.id\n self.value = value\n }\n\n init(idx: UInt8, compressedName name: String, value: [UInt8]) {\n self.name = name\n self.index = idx\n self.value = value\n }\n\n // MARK: Class methods\n public static func compressName(_ name: String) -> (id: UInt8, str: String) {\n for (id, prefix) in prefixMap.sorted(by: { $1.1.count < $0.1.count }) where name.hasPrefix(prefix) {\n return (UInt8(id), String(name.dropFirst(prefix.count)))\n }\n return (0, name)\n }\n\n public static func decompressName(id: Int, suffix: String) -> String {\n guard let prefix = prefixMap[id] else {\n return suffix\n }\n return \"\\(prefix)\\(suffix)\"\n }\n }\n\n public struct FileXattrsState {\n private let inodeCapacity: UInt32\n private let blockCapacity: UInt32\n private let inode: UInt32 // the inode number for which we are tracking these xattrs\n\n var inlineAttributes: [ExtendedAttribute] = []\n var blockAttributes: [ExtendedAttribute] = []\n private var usedSizeInline: UInt32 = 0\n private var usedSizeBlock: UInt32 = 0\n\n private var inodeFreeBytes: UInt32 {\n self.inodeCapacity - EXT4.XattrInodeHeaderSize - usedSizeInline - 4 // need to have 4 null bytes b/w xattr entries and values\n }\n\n private var blockFreeBytes: UInt32 {\n self.blockCapacity - EXT4.XattrBlockHeaderSize - usedSizeBlock - 4\n }\n\n init(inode: UInt32, inodeXattrCapacity: UInt32, blockCapacity: UInt32) {\n self.inode = inode\n self.inodeCapacity = inodeXattrCapacity\n self.blockCapacity = blockCapacity\n }\n\n public mutating func add(_ attribute: ExtendedAttribute) throws {\n let size = attribute.size\n if size <= inodeFreeBytes {\n usedSizeInline += size\n inlineAttributes.append(attribute)\n return\n }\n if size <= blockFreeBytes {\n usedSizeBlock += size\n blockAttributes.append(attribute)\n return\n }\n throw Error.insufficientSpace(Int(self.inode))\n }\n\n public func writeInlineAttributes(buffer: inout [UInt8]) throws {\n var idx = 0\n withUnsafeLittleEndianBytes(\n of: EXT4.XAttrHeaderMagic,\n body: { bytes in\n for byte in bytes {\n buffer[idx] = byte\n idx += 1\n }\n })\n try Self.write(buffer: &buffer, attrs: self.inlineAttributes, start: UInt16(idx), delta: 0, inline: true)\n }\n\n public func writeBlockAttributes(buffer: inout [UInt8]) throws {\n var idx = 0\n for val in [EXT4.XAttrHeaderMagic, 1, 1] {\n withUnsafeLittleEndianBytes(\n of: UInt32(val),\n body: { bytes in\n for byte in bytes {\n buffer[idx] = byte\n idx += 1\n }\n })\n }\n while idx != 32 {\n buffer[idx] = 0\n idx += 1\n }\n var attributes = self.blockAttributes\n attributes.sort(by: {\n if ($0.index < $1.index) || ($0.name.count < $1.name.count) || ($0.name < $1.name) {\n return true\n }\n return false\n })\n try Self.write(buffer: &buffer, attrs: attributes, start: UInt16(idx), delta: UInt16(idx), inline: false)\n }\n\n /// Writes the specified list of extended attribute entries and their values to the provided\n /// This method does not fill in any headers (Inode inline / block level) that may be required to parse these attributes\n ///\n /// - Parameters:\n /// - buffer: An array of [UInt8] where the data will be written into\n /// - attrs: The list of ExtendedAttributes to write\n /// - start: the index from where data should be put into the buffer - useful when if you dont want this method to be overwriting existing data\n /// - delta: index from where the begin the offset calculations\n /// - inline: if the byte buffer being written into is an inline data block for an inode: Determines the hash calculation\n private static func write(\n buffer: inout [UInt8], attrs: [ExtendedAttribute], start: UInt16, delta: UInt16, inline: Bool\n ) throws {\n var offset: UInt16 = UInt16(buffer.count) + delta - start\n var front = Int(start)\n var end = buffer.count\n\n for attribute in attrs {\n guard end - front >= 4 else {\n throw Error.malformedXattrBuffer\n }\n\n var out: [UInt8] = []\n let v = attribute.sizeValue\n offset -= UInt16(v)\n out.append(UInt8(attribute.name.count))\n out.append(attribute.index)\n withUnsafeLittleEndianBytes(\n of: UInt16(offset),\n body: { bytes in\n out.append(contentsOf: bytes)\n })\n out.append(contentsOf: [0, 0, 0, 0]) // these next four bytes indicate that the attr values are in the same block\n withUnsafeLittleEndianBytes(\n of: UInt32(attribute.value.count),\n body: { bytes in\n out.append(contentsOf: bytes)\n })\n if !inline {\n withUnsafeLittleEndianBytes(\n of: UInt32(attribute.hash),\n body: { bytes in\n out.append(contentsOf: bytes)\n })\n } else {\n out.append(contentsOf: [0, 0, 0, 0])\n }\n guard let name = attribute.name.data(using: .ascii) else {\n throw Error.convertAsciiString(attribute.name)\n }\n out.append(contentsOf: [UInt8](name))\n while out.count < Int(attribute.sizeEntry) { // ensure that xattr entry size is a multiple of 4\n out.append(0)\n }\n for (i, byte) in out.enumerated() {\n buffer[front + i] = byte\n }\n front += out.count\n\n end -= Int(attribute.sizeValue)\n for (i, byte) in attribute.value.enumerated() {\n buffer[end + i] = byte\n }\n }\n }\n\n public static func read(buffer: [UInt8], start: Int, offset: Int) throws -> [ExtendedAttribute] {\n var i = start\n var attribs: [ExtendedAttribute] = []\n // 16 is the size of 1 XAttrEntry\n while i + 16 < buffer.count {\n let attributeStart = i\n let rawXattrEntry = Array(buffer[i.. CInt = ioctl\n#endif\n\n/// Thread-safe socket wrapper.\npublic final class Socket: Sendable {\n public enum TimeoutOption {\n case send\n case receive\n }\n\n public enum ShutdownOption {\n case read\n case write\n case readWrite\n }\n\n private enum SocketState {\n case created\n case connected\n case listening\n }\n\n private struct State {\n let socketState: SocketState\n let handle: FileHandle?\n let type: SocketType\n let acceptSource: DispatchSourceRead?\n }\n\n private let _closeOnDeinit: Bool\n private let _queue: DispatchQueue\n\n private let state: Mutex\n\n public var fileDescriptor: Int32 {\n guard let handle = state.withLock({ $0.handle }) else {\n return -1\n }\n return handle.fileDescriptor\n }\n\n public convenience init(type: SocketType, closeOnDeinit: Bool = true) throws {\n let sockFD = sysSocket(type.domain, type.type, 0)\n if sockFD < 0 {\n throw SocketError.withErrno(\"failed to create socket: \\(sockFD)\", errno: errno)\n }\n self.init(fd: sockFD, type: type, closeOnDeinit: closeOnDeinit)\n }\n\n init(fd: Int32, type: SocketType, closeOnDeinit: Bool) {\n _queue = DispatchQueue(label: \"com.apple.containerization.socket\")\n _closeOnDeinit = closeOnDeinit\n let state = State(\n socketState: .created,\n handle: FileHandle(fileDescriptor: fd, closeOnDealloc: false),\n type: type,\n acceptSource: nil\n )\n self.state = Mutex(state)\n }\n\n deinit {\n if _closeOnDeinit {\n try? close()\n }\n }\n}\n\nextension Socket {\n static func errnoToError(msg: String) -> SocketError {\n SocketError.withErrno(\"\\(msg) (\\(_errnoString(errno)))\", errno: errno)\n }\n\n public func connect() throws {\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n guard state.withLock({ $0.socketState }) == .created else {\n throw SocketError.invalidOperationOnSocket(\"connect\")\n }\n\n var res: Int32 = 0\n try state.withLock {\n try $0.type.withSockAddr { (ptr, length) in\n res = Syscall.retrying {\n sysConnect(handle.fileDescriptor, ptr, length)\n }\n }\n }\n if res == -1 {\n throw Socket.errnoToError(msg: \"could not connect to socket \\(state.withLock { $0.type })\")\n }\n state.withLock {\n $0 = State(\n socketState: .connected,\n handle: handle,\n type: $0.type,\n acceptSource: $0.acceptSource\n )\n }\n }\n\n public func listen() throws {\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n guard state.withLock({ $0.socketState }) == .created else {\n throw SocketError.invalidOperationOnSocket(\"listen\")\n }\n\n try state.withLock { try $0.type.beforeBind(fd: handle.fileDescriptor) }\n\n var rc: Int32 = 0\n try state.withLock {\n try $0.type.withSockAddr { (ptr, length) in\n rc = sysBind(handle.fileDescriptor, ptr, length)\n }\n }\n if rc < 0 {\n throw Socket.errnoToError(msg: \"could not bind to \\(state.withLock { $0.type })\")\n }\n\n try state.withLock { try $0.type.beforeListen(fd: handle.fileDescriptor) }\n if sysListen(handle.fileDescriptor, SOMAXCONN) < 0 {\n throw Socket.errnoToError(msg: \"listen failed on \\(state.withLock { $0.type })\")\n }\n state.withLock {\n $0 = State(\n socketState: .listening,\n handle: handle,\n type: $0.type,\n acceptSource: $0.acceptSource\n )\n }\n }\n\n public func close() throws {\n // Already closed.\n guard let handle = state.withLock({ $0.handle }) else {\n return\n }\n if let acceptSource = state.withLock({ $0.acceptSource }) {\n acceptSource.cancel()\n }\n try handle.close()\n state.withLock {\n $0 = State(\n socketState: $0.socketState,\n handle: nil,\n type: $0.type,\n acceptSource: nil\n )\n }\n }\n\n public func write(data: any DataProtocol) throws -> Int {\n guard state.withLock({ $0.socketState }) == .connected else {\n throw SocketError.invalidOperationOnSocket(\"write\")\n }\n\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n if data.isEmpty {\n return 0\n }\n\n try handle.write(contentsOf: data)\n return data.count\n }\n\n public func acceptStream(closeOnDeinit: Bool = true) throws -> AsyncThrowingStream {\n guard state.withLock({ $0.socketState }) == .listening else {\n throw SocketError.invalidOperationOnSocket(\"accept\")\n }\n\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n guard state.withLock({ $0.acceptSource }) == nil else {\n throw SocketError.acceptStreamExists\n }\n\n let source = state.withLock {\n let source = DispatchSource.makeReadSource(\n fileDescriptor: handle.fileDescriptor,\n queue: _queue\n )\n $0 = State(\n socketState: $0.socketState,\n handle: handle,\n type: $0.type,\n acceptSource: source\n )\n return source\n }\n\n return AsyncThrowingStream { cont in\n source.setCancelHandler {\n cont.finish()\n }\n source.setEventHandler(handler: {\n if source.data == 0 {\n source.cancel()\n return\n }\n\n do {\n let connection = try self.accept(closeOnDeinit: closeOnDeinit)\n cont.yield(connection)\n } catch SocketError.closed {\n source.cancel()\n } catch {\n cont.yield(with: .failure(error))\n source.cancel()\n }\n })\n source.activate()\n }\n }\n\n public func accept(closeOnDeinit: Bool = true) throws -> Socket {\n guard state.withLock({ $0.socketState }) == .listening else {\n throw SocketError.invalidOperationOnSocket(\"accept\")\n }\n\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n let (clientFD, socketType) = try state.withLock { try $0.type.accept(fd: handle.fileDescriptor) }\n return Socket(\n fd: clientFD,\n type: socketType,\n closeOnDeinit: closeOnDeinit\n )\n }\n\n public func read(buffer: inout Data) throws -> Int {\n guard state.withLock({ $0.socketState }) == .connected else {\n throw SocketError.invalidOperationOnSocket(\"read\")\n }\n\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n var bytesRead = 0\n let bufferSize = buffer.count\n try buffer.withUnsafeMutableBytes { pointer in\n guard let baseAddress = pointer.baseAddress else {\n throw SocketError.missingBaseAddress\n }\n\n bytesRead = Syscall.retrying {\n sysRead(handle.fileDescriptor, baseAddress, bufferSize)\n }\n if bytesRead < 0 {\n throw Socket.errnoToError(msg: \"Error reading from connection\")\n } else if bytesRead == 0 {\n throw SocketError.closed\n }\n }\n return bytesRead\n }\n\n public func shutdown(how: ShutdownOption) throws {\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n var howOpt: Int32 = 0\n switch how {\n case .read:\n howOpt = Int32(SHUT_RD)\n case .write:\n howOpt = Int32(SHUT_WR)\n case .readWrite:\n howOpt = Int32(SHUT_RDWR)\n }\n\n if sysShutdown(handle.fileDescriptor, howOpt) < 0 {\n throw Socket.errnoToError(msg: \"shutdown failed\")\n }\n }\n\n public func setSockOpt(sockOpt: Int32 = 0, ptr: UnsafeRawPointer, stride: UInt32) throws {\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n if setsockopt(handle.fileDescriptor, SOL_SOCKET, sockOpt, ptr, stride) < 0 {\n throw Socket.errnoToError(msg: \"failed to set sockopt\")\n }\n }\n\n public func setTimeout(option: TimeoutOption, seconds: Int) throws {\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n var sockOpt: Int32 = 0\n switch option {\n case .receive:\n sockOpt = SO_RCVTIMEO\n case .send:\n sockOpt = SO_SNDTIMEO\n }\n\n var timer = timeval()\n timer.tv_sec = seconds\n timer.tv_usec = 0\n\n if setsockopt(\n handle.fileDescriptor,\n SOL_SOCKET,\n sockOpt,\n &timer,\n socklen_t(MemoryLayout.size)\n ) < 0 {\n throw Socket.errnoToError(msg: \"failed to set read timeout\")\n }\n }\n\n static func _errnoString(_ err: Int32?) -> String {\n String(validatingCString: strerror(errno)) ?? \"error: \\(errno)\"\n }\n}\n\npublic enum SocketError: Error, Equatable, CustomStringConvertible {\n case closed\n case acceptStreamExists\n case invalidOperationOnSocket(String)\n case missingBaseAddress\n case withErrno(_ msg: String, errno: Int32)\n\n public var description: String {\n switch self {\n case .closed:\n return \"socket: closed\"\n case .acceptStreamExists:\n return \"accept stream already exists\"\n case .invalidOperationOnSocket(let operation):\n return \"socket: invalid operation on socket '\\(operation)'\"\n case .missingBaseAddress:\n return \"socket: missing base address\"\n case .withErrno(let msg, _):\n return \"socket: error \\(msg)\"\n }\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/VsockProxy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationIO\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport SendableProperty\n\nfinal class VsockProxy: Sendable {\n enum Action {\n case listen\n case dial\n }\n\n private enum SocketType {\n case unix\n case vsock\n }\n\n init(\n id: String,\n action: Action,\n port: UInt32,\n path: URL,\n udsPerms: UInt32?,\n log: Logger? = nil\n ) {\n self.id = id\n self.action = action\n self.port = port\n self.path = path\n self.udsPerms = udsPerms\n self.log = log\n }\n\n public let id: String\n private let path: URL\n private let action: Action\n private let port: UInt32\n private let udsPerms: UInt32?\n private let log: Logger?\n\n @SendableProperty\n private var listener: Socket?\n private let task = Mutex?>(nil)\n}\n\nextension VsockProxy {\n func close() throws {\n guard let listener else {\n return\n }\n\n try listener.close()\n let fm = FileManager.default\n if fm.fileExists(atPath: self.path.path) {\n try FileManager.default.removeItem(at: self.path)\n }\n let task = task.withLock { $0 }\n task?.cancel()\n }\n\n func start() throws {\n switch self.action {\n case .dial:\n try dialHost()\n case .listen:\n try dialGuest()\n }\n }\n\n private func dialHost() throws {\n let fm = FileManager.default\n\n let parentDir = self.path.deletingLastPathComponent()\n try fm.createDirectory(\n at: parentDir,\n withIntermediateDirectories: true\n )\n\n let type = try UnixType(\n path: self.path.path,\n perms: self.udsPerms,\n unlinkExisting: true\n )\n let uds = try Socket(type: type)\n try uds.listen()\n listener = uds\n\n try self.acceptLoop(socketType: .unix)\n }\n\n private func dialGuest() throws {\n let type = VsockType(\n port: self.port,\n cid: VsockType.anyCID\n )\n let vsock = try Socket(type: type)\n try vsock.listen()\n listener = vsock\n\n try self.acceptLoop(socketType: .vsock)\n }\n\n private func acceptLoop(socketType: SocketType) throws {\n guard let listener else {\n return\n }\n\n let stream = try listener.acceptStream()\n let task = Task {\n do {\n for try await conn in stream {\n Task {\n do {\n try await handleConn(\n conn: conn,\n connType: socketType\n )\n } catch {\n self.log?.error(\"failed to handle connection: \\(error)\")\n }\n }\n }\n } catch {\n self.log?.error(\"failed to accept connection: \\(error)\")\n }\n }\n self.task.withLock { $0 = task }\n }\n\n private func handleConn(\n conn: ContainerizationOS.Socket,\n connType: SocketType\n ) async throws {\n try await withCheckedThrowingContinuation { (c: CheckedContinuation) in\n do {\n // `relayTo` isn't used concurrently.\n nonisolated(unsafe) var relayTo: ContainerizationOS.Socket\n\n switch connType {\n case .unix:\n let type = VsockType(\n port: self.port,\n cid: VsockType.hostCID\n )\n relayTo = try Socket(\n type: type,\n closeOnDeinit: false\n )\n case .vsock:\n let type = try UnixType(path: self.path.path)\n relayTo = try Socket(\n type: type,\n closeOnDeinit: false\n )\n }\n\n try relayTo.connect()\n\n // `clientFile` isn't used concurrently.\n nonisolated(unsafe) var clientFile = OSFile.SpliceFile(fd: conn.fileDescriptor)\n // `serverFile` isn't used concurrently.\n nonisolated(unsafe) var serverFile = OSFile.SpliceFile(fd: relayTo.fileDescriptor)\n\n let cleanup = { @Sendable in\n do {\n try ProcessSupervisor.default.poller.delete(clientFile.fileDescriptor)\n try ProcessSupervisor.default.poller.delete(serverFile.fileDescriptor)\n try conn.close()\n try relayTo.close()\n } catch {\n self.log?.error(\"Failed to clean up vsock proxy: \\(error)\")\n }\n c.resume()\n }\n\n try! ProcessSupervisor.default.poller.add(clientFile.fileDescriptor, mask: EPOLLIN | EPOLLOUT) { mask in\n if mask.readyToRead {\n do {\n let (_, _, action) = try OSFile.splice(from: &clientFile, to: &serverFile)\n if action == .eof || action == .brokenPipe {\n return cleanup()\n }\n } catch {\n return cleanup()\n }\n }\n\n if mask.readyToWrite {\n do {\n let (_, _, action) = try OSFile.splice(from: &serverFile, to: &clientFile)\n if action == .eof || action == .brokenPipe {\n return cleanup()\n }\n } catch {\n return cleanup()\n }\n }\n\n if mask.isHangup {\n return cleanup()\n }\n }\n\n try! ProcessSupervisor.default.poller.add(serverFile.fileDescriptor, mask: EPOLLIN | EPOLLOUT) { mask in\n if mask.readyToRead {\n do {\n let (_, _, action) = try OSFile.splice(from: &serverFile, to: &clientFile)\n if action == .eof || action == .brokenPipe {\n return cleanup()\n }\n } catch {\n return cleanup()\n }\n }\n\n if mask.readyToWrite {\n do {\n let (_, _, action) = try OSFile.splice(from: &clientFile, to: &serverFile)\n if action == .eof || action == .brokenPipe {\n return cleanup()\n }\n } catch {\n return cleanup()\n }\n }\n\n if mask.isHangup {\n return cleanup()\n }\n }\n } catch {\n c.resume(throwing: error)\n }\n }\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/Server.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\nimport GRPC\nimport Logging\nimport Musl\nimport NIOCore\nimport NIOPosix\n\nfinal class Initd: Sendable {\n let log: Logger\n let state: State\n let group: MultiThreadedEventLoopGroup\n\n actor State {\n var containers: [String: ManagedContainer] = [:]\n var proxies: [String: VsockProxy] = [:]\n\n func get(container id: String) throws -> ManagedContainer {\n guard let ctr = self.containers[id] else {\n throw ContainerizationError(\n .notFound,\n message: \"container \\(id) not found\"\n )\n }\n return ctr\n }\n\n func add(container: ManagedContainer) throws {\n guard containers[container.id] == nil else {\n throw ContainerizationError(\n .exists,\n message: \"container \\(container.id) already exists\"\n )\n }\n containers[container.id] = container\n }\n\n func add(proxy: VsockProxy) throws {\n guard proxies[proxy.id] == nil else {\n throw ContainerizationError(\n .exists,\n message: \"proxy \\(proxy.id) already exists\"\n )\n }\n proxies[proxy.id] = proxy\n }\n\n func remove(proxy id: String) throws -> VsockProxy {\n guard let proxy = proxies.removeValue(forKey: id) else {\n throw ContainerizationError(\n .notFound,\n message: \"proxy \\(id) does not exist\"\n )\n }\n return proxy\n }\n\n func remove(container id: String) throws {\n guard let _ = containers.removeValue(forKey: id) else {\n throw ContainerizationError(\n .notFound,\n message: \"container \\(id) does not exist\"\n )\n }\n }\n }\n\n init(log: Logger, group: MultiThreadedEventLoopGroup) {\n self.log = log\n self.group = group\n self.state = State()\n }\n\n func serve(port: Int) async throws {\n try await withThrowingTaskGroup(of: Void.self) { group in\n log.debug(\"starting process supervisor\")\n\n await ProcessSupervisor.default.setLog(self.log)\n await ProcessSupervisor.default.ready()\n\n log.debug(\n \"booting grpc server on vsock\",\n metadata: [\n \"port\": \"\\(port)\"\n ])\n let server = try await Server.start(\n configuration: .default(\n target: .vsockAddress(.init(cid: .any, port: .init(port))),\n eventLoopGroup: self.group,\n serviceProviders: [self])\n ).get()\n log.info(\n \"grpc api serving on vsock\",\n metadata: [\n \"port\": \"\\(port)\"\n ])\n\n group.addTask {\n try await server.onClose.get()\n }\n try await group.next()\n group.cancelAll()\n }\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/ManagedProcess.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport GRPC\nimport Logging\nimport Synchronization\n\nfinal class ManagedProcess: Sendable {\n let id: String\n\n private let log: Logger\n private let process: Command\n private let lock: Mutex\n private let syncfd: Pipe\n private let owningPid: Int32?\n\n private struct State {\n init(io: IO) {\n self.io = io\n }\n\n let io: IO\n var waiters: [CheckedContinuation] = []\n var exitStatus: Int32? = nil\n var pid: Int32 = 0\n }\n\n var pid: Int32 {\n self.lock.withLock {\n $0.pid\n }\n }\n\n // swiftlint: disable type_name\n protocol IO {\n func start(process: inout Command) throws\n func closeAfterExec() throws\n func resize(size: Terminal.Size) throws\n func closeStdin() throws\n }\n // swiftlint: enable type_name\n\n static func localizeLogger(log: inout Logger, id: String) {\n log[metadataKey: \"id\"] = \"\\(id)\"\n }\n\n init(\n id: String,\n stdio: HostStdio,\n bundle: ContainerizationOCI.Bundle,\n owningPid: Int32? = nil,\n log: Logger\n ) throws {\n self.id = id\n var log = log\n Self.localizeLogger(log: &log, id: id)\n self.log = log\n self.owningPid = owningPid\n\n let syncfd = Pipe()\n try syncfd.setCloexec()\n self.syncfd = syncfd\n\n let args: [String]\n if let owningPid {\n args = [\n \"exec\",\n \"--parent-pid\",\n \"\\(owningPid)\",\n \"--process-path\",\n bundle.getExecSpecPath(id: id).path,\n ]\n } else {\n args = [\"run\", \"--bundle-path\", bundle.path.path]\n }\n\n var process = Command(\n \"/sbin/vmexec\",\n arguments: args,\n extraFiles: [syncfd.fileHandleForWriting]\n )\n\n var io: IO\n if stdio.terminal {\n log.info(\"setting up terminal IO\")\n let attrs = Command.Attrs(setsid: false, setctty: false)\n process.attrs = attrs\n io = try TerminalIO(\n stdio: stdio,\n log: log\n )\n } else {\n process.attrs = .init(setsid: false)\n io = StandardIO(\n stdio: stdio,\n log: log\n )\n }\n\n log.info(\"starting io\")\n\n // Setup IO early. We expect the host to be listening already.\n try io.start(process: &process)\n\n self.process = process\n self.lock = Mutex(State(io: io))\n }\n}\n\nextension ManagedProcess {\n func start() throws -> Int32 {\n try self.lock.withLock {\n log.info(\n \"starting managed process\",\n metadata: [\n \"id\": \"\\(id)\"\n ])\n\n // Start the underlying process.\n try process.start()\n\n // Close our side of any pipes.\n try syncfd.fileHandleForWriting.close()\n try $0.io.closeAfterExec()\n\n guard let piddata = try syncfd.fileHandleForReading.readToEnd() else {\n throw ContainerizationError(.internalError, message: \"no pid data from sync pipe\")\n }\n\n let i = piddata.withUnsafeBytes { ptr in\n ptr.load(as: Int32.self)\n }\n\n log.info(\"got back pid data \\(i)\")\n $0.pid = i\n\n log.info(\n \"started managed process\",\n metadata: [\n \"pid\": \"\\(i)\",\n \"id\": \"\\(id)\",\n ])\n\n return i\n }\n }\n\n func setExit(_ status: Int32) {\n self.lock.withLock {\n self.log.info(\n \"managed process exit\",\n metadata: [\n \"status\": \"\\(status)\"\n ])\n\n $0.exitStatus = status\n\n for waiter in $0.waiters {\n waiter.resume(returning: status)\n }\n\n self.log.debug(\"\\($0.waiters.count) managed process waiters signaled\")\n $0.waiters.removeAll()\n }\n }\n\n /// Wait on the process to exit\n func wait() async -> Int32 {\n await withCheckedContinuation { cont in\n self.lock.withLock {\n if let status = $0.exitStatus {\n cont.resume(returning: status)\n return\n }\n $0.waiters.append(cont)\n }\n }\n }\n\n func kill(_ signal: Int32) throws {\n try self.lock.withLock {\n guard $0.exitStatus == nil else {\n return\n }\n\n self.log.info(\"sending signal \\(signal) to process \\($0.pid)\")\n guard Foundation.kill($0.pid, signal) == 0 else {\n throw POSIXError.fromErrno()\n }\n }\n }\n\n func resize(size: Terminal.Size) throws {\n try self.lock.withLock {\n guard $0.exitStatus == nil else {\n return\n }\n try $0.io.resize(size: size)\n }\n }\n\n func closeStdin() throws {\n try self.lock.withLock {\n try $0.io.closeStdin()\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/Reader.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CArchive\nimport Foundation\n\n/// A class responsible for reading entries from an archive file.\npublic final class ArchiveReader {\n /// A pointer to the underlying `archive` C structure.\n var underlying: OpaquePointer?\n /// The file handle associated with the archive file being read.\n let fileHandle: FileHandle?\n\n /// Initializes an `ArchiveReader` to read from a specified file URL with an explicit `Format` and `Filter`.\n /// Note: This method must be used when it is known that the archive at the specified URL follows the specified\n /// `Format` and `Filter`.\n public convenience init(format: Format, filter: Filter, file: URL) throws {\n let fileHandle = try FileHandle(forReadingFrom: file)\n try self.init(format: format, filter: filter, fileHandle: fileHandle)\n }\n\n /// Initializes an `ArchiveReader` to read from the provided file descriptor with an explicit `Format` and `Filter`.\n /// Note: This method must be used when it is known that the archive pointed to by the file descriptor follows the specified\n /// `Format` and `Filter`.\n public init(format: Format, filter: Filter, fileHandle: FileHandle) throws {\n self.underlying = archive_read_new()\n self.fileHandle = fileHandle\n\n try archive_read_set_format(underlying, format.code)\n .checkOk(elseThrow: .unableToSetFormat(format.code, format))\n try archive_read_append_filter(underlying, filter.code)\n .checkOk(elseThrow: .unableToAddFilter(filter.code, filter))\n\n let fd = fileHandle.fileDescriptor\n try archive_read_open_fd(underlying, fd, 4096)\n .checkOk(elseThrow: { .unableToOpenArchive($0) })\n }\n\n /// Initialize the `ArchiveReader` to read from a specified file URL\n /// by trying to auto determine the archives `Format` and `Filter`.\n public init(file: URL) throws {\n self.underlying = archive_read_new()\n let fileHandle = try FileHandle(forReadingFrom: file)\n self.fileHandle = fileHandle\n try archive_read_support_filter_all(underlying)\n .checkOk(elseThrow: .failedToDetectFilter)\n try archive_read_support_format_all(underlying)\n .checkOk(elseThrow: .failedToDetectFormat)\n let fd = fileHandle.fileDescriptor\n try archive_read_open_fd(underlying, fd, 4096)\n .checkOk(elseThrow: { .unableToOpenArchive($0) })\n }\n\n deinit {\n archive_read_free(underlying)\n try? fileHandle?.close()\n }\n}\n\nextension CInt {\n fileprivate func checkOk(elseThrow error: @autoclosure () -> ArchiveError) throws {\n guard self == ARCHIVE_OK else { throw error() }\n }\n fileprivate func checkOk(elseThrow error: (CInt) -> ArchiveError) throws {\n guard self == ARCHIVE_OK else { throw error(self) }\n }\n\n}\n\nextension ArchiveReader: Sequence {\n public func makeIterator() -> Iterator {\n Iterator(reader: self)\n }\n\n public struct Iterator: IteratorProtocol {\n var reader: ArchiveReader\n\n public mutating func next() -> (WriteEntry, Data)? {\n let entry = WriteEntry()\n let result = archive_read_next_header2(reader.underlying, entry.underlying)\n if result == ARCHIVE_EOF {\n return nil\n }\n let data = reader.readDataForEntry(entry)\n return (entry, data)\n }\n }\n\n internal func readDataForEntry(_ entry: WriteEntry) -> Data {\n let bufferSize = Int(Swift.min(entry.size ?? 4096, 4096))\n var entry = Data()\n var part = Data(count: bufferSize)\n while true {\n let c = part.withUnsafeMutableBytes { buffer in\n guard let baseAddress = buffer.baseAddress else {\n return 0\n }\n return archive_read_data(self.underlying, baseAddress, buffer.count)\n }\n guard c > 0 else { break }\n part.count = c\n entry.append(part)\n }\n return entry\n }\n}\n\nextension ArchiveReader {\n public convenience init(name: String, bundle: Data, tempDirectoryBaseName: String? = nil) throws {\n let baseName = tempDirectoryBaseName ?? \"Unarchiver\"\n let url = createTemporaryDirectory(baseName: baseName)!.appendingPathComponent(name)\n try bundle.write(to: url, options: .atomic)\n try self.init(format: .zip, filter: .none, file: url)\n }\n\n /// Extracts the contents of an archive to the provided directory.\n /// Currently only handles regular files and directories present in the archive.\n public func extractContents(to directory: URL) throws {\n let fm = FileManager.default\n var foundEntry = false\n for (entry, data) in self {\n guard let p = entry.path else { continue }\n foundEntry = true\n let type = entry.fileType\n let target = directory.appending(path: p)\n switch type {\n case .regular:\n try data.write(to: target, options: .atomic)\n case .directory:\n try fm.createDirectory(at: target, withIntermediateDirectories: true)\n case .symbolicLink:\n guard let symlinkTarget = entry.symlinkTarget, let linkTargetURL = URL(string: symlinkTarget, relativeTo: target) else {\n continue\n }\n try fm.createSymbolicLink(at: target, withDestinationURL: linkTargetURL)\n default:\n continue\n }\n chmod(target.path(), entry.permissions)\n if let owner = entry.owner, let group = entry.group {\n chown(target.path(), owner, group)\n }\n }\n guard foundEntry else {\n throw ArchiveError.failedToExtractArchive(\"No entries found in archive\")\n }\n }\n\n /// This method extracts a given file from the archive.\n /// This operation modifies the underlying file descriptor's position within the archive,\n /// meaning subsequent reads will start from a new location.\n /// To reset the underlying file descriptor to the beginning of the archive, close and\n /// reopen the archive.\n public func extractFile(path: String) throws -> (WriteEntry, Data) {\n let entry = WriteEntry()\n while archive_read_next_header2(self.underlying, entry.underlying) != ARCHIVE_EOF {\n guard let entryPath = entry.path else { continue }\n let trimCharSet = CharacterSet(charactersIn: \"./\")\n let trimmedEntry = entryPath.trimmingCharacters(in: trimCharSet)\n let trimmedRequired = path.trimmingCharacters(in: trimCharSet)\n guard trimmedEntry == trimmedRequired else { continue }\n let data = readDataForEntry(entry)\n return (entry, data)\n }\n throw ArchiveError.failedToExtractArchive(\" \\(path) not found in archive\")\n }\n}\n"], ["/containerization/Sources/Containerization/VZVirtualMachineManager.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport Logging\n\n/// A virtualization.framework backed `VirtualMachineManager` implementation.\npublic struct VZVirtualMachineManager: VirtualMachineManager {\n private let kernel: Kernel\n private let bootlog: String?\n private let initialFilesystem: Mount\n private let logger: Logger?\n\n public init(\n kernel: Kernel,\n initialFilesystem: Mount,\n bootlog: String? = nil,\n logger: Logger? = nil\n ) {\n self.kernel = kernel\n self.bootlog = bootlog\n self.initialFilesystem = initialFilesystem\n self.logger = logger\n }\n\n public func create(container: Container) throws -> any VirtualMachineInstance {\n guard let c = container as? LinuxContainer else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"provided container is not a LinuxContainer\"\n )\n }\n\n return try VZVirtualMachineInstance(\n logger: self.logger,\n with: { config in\n config.cpus = container.cpus\n config.memoryInBytes = container.memoryInBytes\n\n config.kernel = self.kernel\n config.initialFilesystem = self.initialFilesystem\n\n config.interfaces = container.interfaces\n if let bootlog {\n config.bootlog = URL(filePath: bootlog)\n }\n config.rosetta = c.config.rosetta\n config.nestedVirtualization = c.config.virtualization\n\n config.mounts = [c.rootfs] + c.config.mounts\n })\n }\n}\n#endif\n"], ["/containerization/Sources/Containerization/Image/InitImage.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\n/// Data representing the image to use as the root filesystem for a virtual machine.\n/// Typically this image would contain the guest agent used to facilitate container\n/// workloads, as well as any extras that may be useful to have in the guest.\npublic struct InitImage: Sendable {\n public var name: String { image.reference }\n\n let image: Image\n\n public init(image: Image) {\n self.image = image\n }\n}\n\nextension InitImage {\n /// Unpack the initial filesystem for the desired platform at a given path.\n public func initBlock(at: URL, for platform: SystemPlatform) async throws -> Mount {\n let unpacker = EXT4Unpacker(blockSizeInBytes: 512.mib())\n var fs = try await unpacker.unpack(self.image, for: platform.ociPlatform(), at: at)\n fs.options = [\"ro\"]\n return fs\n }\n\n /// Create a new InitImage with the reference as the name.\n /// The `rootfs` parameter must be a tar.gz file whose contents make up the filesystem for the image.\n public static func create(\n reference: String, rootfs: URL, platform: Platform,\n labels: [String: String] = [:], imageStore: ImageStore, contentStore: ContentStore\n ) async throws -> InitImage {\n\n let indexDescriptorStore = AsyncStore()\n try await contentStore.ingest { dir in\n let writer = try ContentWriter(for: dir)\n var result = try writer.create(from: rootfs)\n let layerDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.imageLayerGzip, digest: result.digest.digestString, size: result.size)\n\n // TODO: compute and fill in the correct diffID for the above layer\n // We currently put in the sha of the fully compressed layer, this needs to be replaced with\n // the sha of the uncompressed layer.\n let rootfsConfig = ContainerizationOCI.Rootfs(type: \"layers\", diffIDs: [result.digest.digestString])\n let runtimeConfig = ContainerizationOCI.ImageConfig(labels: labels)\n let imageConfig = ContainerizationOCI.Image(architecture: platform.architecture, os: platform.os, config: runtimeConfig, rootfs: rootfsConfig)\n result = try writer.create(from: imageConfig)\n let configDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.imageConfig, digest: result.digest.digestString, size: result.size)\n\n let manifest = Manifest(config: configDescriptor, layers: [layerDescriptor])\n result = try writer.create(from: manifest)\n let manifestDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.imageManifest, digest: result.digest.digestString, size: result.size, platform: platform)\n\n let index = ContainerizationOCI.Index(manifests: [manifestDescriptor])\n result = try writer.create(from: index)\n\n let indexDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.index, digest: result.digest.digestString, size: result.size)\n await indexDescriptorStore.set(indexDescriptor)\n\n }\n\n guard let indexDescriptor = await indexDescriptorStore.get() else {\n throw ContainerizationError(.notFound, message: \"image for \\(reference) not found\")\n }\n\n let description = Image.Description(reference: reference, descriptor: indexDescriptor)\n let image = try await imageStore.create(description: description)\n return InitImage(image: image)\n }\n}\n"], ["/containerization/Sources/Containerization/Image/ImageStore/ImageStore+OCILayout.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\nextension ImageStore {\n /// Exports the specified images and their associated layers to an OCI Image Layout directory.\n /// This function saves the images identified by the `references` array, including their\n /// manifests and layer blobs, into a directory structure compliant with the OCI Image Layout specification at the given `out` URL.\n ///\n /// - Parameters:\n /// - references: A list image references that exists in the `ImageStore` that are to be saved in the OCI Image Layout format.\n /// - out: A URL to a directory on disk at which the OCI Image Layout structure will be created.\n /// - platform: An optional parameter to indicate the platform to be saved for the images.\n /// Defaults to `nil` signifying that layers for all supported platforms by the images will be saved.\n ///\n public func save(references: [String], out: URL, platform: Platform? = nil) async throws {\n let matcher = createPlatformMatcher(for: platform)\n let fileManager = FileManager.default\n let tempDir = fileManager.uniqueTemporaryDirectory()\n defer {\n try? fileManager.removeItem(at: tempDir)\n }\n\n var toSave: [Image] = []\n for reference in references {\n let image = try await self.get(reference: reference)\n let allowedMediaTypes = [MediaTypes.dockerManifestList, MediaTypes.index]\n guard allowedMediaTypes.contains(image.mediaType) else {\n throw ContainerizationError(.internalError, message: \"Cannot save image \\(image.reference) with Index media type \\(image.mediaType)\")\n }\n toSave.append(image)\n }\n let client = try LocalOCILayoutClient(root: out)\n var saved: [Descriptor] = []\n\n for image in toSave {\n let ref = try Reference.parse(image.reference)\n let name = ref.path\n guard let tag = ref.tag ?? ref.digest else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid tag/digest for image reference \\(image.reference)\")\n }\n let operation = ExportOperation(name: name, tag: tag, contentStore: self.contentStore, client: client, progress: nil)\n var descriptor = try await operation.export(index: image.descriptor, platforms: matcher)\n client.setImageReferenceAnnotation(descriptor: &descriptor, reference: image.reference)\n saved.append(descriptor)\n }\n try client.createOCILayoutStructure(directory: out, manifests: saved)\n }\n\n /// Imports one or more images and their associated layers from an OCI Image Layout directory.\n ///\n /// - Parameters:\n /// - directory: A URL to a directory on disk at that follows the OCI Image Layout structure.\n /// - progress: An optional handler over which progress update events about the load operation can be received.\n /// - Returns: The list of images that were loaded into the `ImageStore`.\n ///\n public func load(from directory: URL, progress: ProgressHandler? = nil) async throws -> [Image] {\n let client = try LocalOCILayoutClient(root: directory)\n let index = try client.loadIndexFromOCILayout(directory: directory)\n let matcher = createPlatformMatcher(for: nil)\n\n var loaded: [Image.Description] = []\n let (id, tempDir) = try await self.contentStore.newIngestSession()\n do {\n for descriptor in index.manifests {\n guard let reference = client.getImageReferencefromDescriptor(descriptor: descriptor) else {\n continue\n }\n let ref = try Reference.parse(reference)\n let name = ref.path\n let operation = ImportOperation(name: name, contentStore: self.contentStore, client: client, ingestDir: tempDir, progress: progress)\n let indexDesc = try await operation.import(root: descriptor, matcher: matcher)\n loaded.append(Image.Description(reference: reference, descriptor: indexDesc))\n }\n\n let loadedImages = loaded\n let importedImages = try await self.lock.withLock { lock in\n var images: [Image] = []\n try await self.contentStore.completeIngestSession(id)\n for description in loadedImages {\n let img = try await self._create(description: description, lock: lock)\n images.append(img)\n }\n return images\n }\n guard importedImages.count > 0 else {\n throw ContainerizationError(.internalError, message: \"Failed to import image\")\n }\n return importedImages\n } catch {\n try? await self.contentStore.cancelIngestSession(id)\n throw error\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/Formatter+Unpack.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationArchive\nimport Foundation\nimport ContainerizationOS\nimport SystemPackage\nimport ContainerizationExtras\n\nprivate typealias Hardlinks = [FilePath: FilePath]\n\nextension EXT4.Formatter {\n /// Unpack the provided archive on to the ext4 filesystem.\n public func unpack(reader: ArchiveReader, progress: ProgressHandler? = nil) throws {\n var hardlinks: Hardlinks = [:]\n for (entry, data) in reader {\n try Task.checkCancellation()\n guard var pathEntry = entry.path else {\n continue\n }\n\n defer {\n // Count the number of entries\n if let progress {\n Task {\n await progress([\n ProgressEvent(event: \"add-items\", value: 1)\n ])\n }\n }\n }\n\n pathEntry = preProcessPath(s: pathEntry)\n let path = FilePath(pathEntry)\n\n if path.base.hasPrefix(\".wh.\") {\n if path.base == \".wh..wh..opq\" { // whiteout directory\n try self.unlink(path: path.dir, directoryWhiteout: true)\n continue\n }\n let startIndex = path.base.index(path.base.startIndex, offsetBy: \".wh.\".count)\n let filePath = String(path.base[startIndex...])\n let dir: FilePath = path.dir\n try self.unlink(path: dir.join(filePath))\n continue\n }\n\n if let hardlink = entry.hardlink {\n let hl = preProcessPath(s: hardlink)\n hardlinks[path] = FilePath(hl)\n continue\n }\n let ts = FileTimestamps(\n access: entry.contentAccessDate, modification: entry.modificationDate, creation: entry.creationDate)\n switch entry.fileType {\n case .directory:\n try self.create(\n path: path, mode: EXT4.Inode.Mode(.S_IFDIR, entry.permissions), ts: ts, uid: entry.owner,\n gid: entry.group,\n xattrs: entry.xattrs)\n case .regular:\n let inputStream = InputStream(data: data)\n inputStream.open()\n try self.create(\n path: path, mode: EXT4.Inode.Mode(.S_IFREG, entry.permissions), ts: ts, buf: inputStream,\n uid: entry.owner,\n gid: entry.group, xattrs: entry.xattrs)\n inputStream.close()\n\n // Count the size of files\n if let progress {\n Task {\n let size = Int64(data.count)\n await progress([\n ProgressEvent(event: \"add-size\", value: size)\n ])\n }\n }\n case .symbolicLink:\n var symlinkTarget: FilePath?\n if let target = entry.symlinkTarget {\n symlinkTarget = FilePath(target)\n }\n try self.create(\n path: path, link: symlinkTarget, mode: EXT4.Inode.Mode(.S_IFLNK, entry.permissions), ts: ts,\n uid: entry.owner,\n gid: entry.group, xattrs: entry.xattrs)\n default:\n continue\n }\n }\n guard hardlinks.acyclic else {\n throw UnpackError.circularLinks\n }\n for (path, _) in hardlinks {\n if let resolvedTarget = try hardlinks.resolve(path) {\n try self.link(link: path, target: resolvedTarget)\n }\n }\n }\n\n /// Unpack an archive at the source URL on to the ext4 filesystem.\n public func unpack(\n source: URL,\n format: ContainerizationArchive.Format = .paxRestricted,\n compression: ContainerizationArchive.Filter = .gzip,\n progress: ProgressHandler? = nil\n ) throws {\n let reader = try ArchiveReader(\n format: format,\n filter: compression,\n file: source\n )\n try self.unpack(reader: reader, progress: progress)\n }\n\n private func preProcessPath(s: String) -> String {\n var p = s\n if p.hasPrefix(\"./\") {\n p = String(p.dropFirst())\n }\n if !p.hasPrefix(\"/\") {\n p = \"/\" + p\n }\n return p\n }\n}\n\n/// Common errors for unpacking an archive onto an ext4 filesystem.\npublic enum UnpackError: Swift.Error, CustomStringConvertible, Sendable, Equatable {\n /// The name is invalid.\n case invalidName(_ name: String)\n /// A circular link is found.\n case circularLinks\n\n /// The description of the error.\n public var description: String {\n switch self {\n case .invalidName(let name):\n return \"'\\(name)' is an invalid name\"\n case .circularLinks:\n return \"circular links found\"\n }\n }\n}\n\nextension Hardlinks {\n fileprivate var acyclic: Bool {\n for (_, target) in self {\n var visited: Set = [target]\n var next = target\n while let item = self[next] {\n if visited.contains(item) {\n return false\n }\n next = item\n visited.insert(next)\n }\n }\n return true\n }\n\n fileprivate func resolve(_ key: FilePath) throws -> FilePath? {\n let target = self[key]\n guard let target else {\n return nil\n }\n var next = target\n let visited: Set = [next]\n while let item = self[next] {\n if visited.contains(item) {\n throw UnpackError.circularLinks\n }\n next = item\n }\n return next\n }\n}\n#endif\n"], ["/containerization/Sources/cctl/cctl.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationOCI\nimport Foundation\nimport Logging\n\nlet log = {\n LoggingSystem.bootstrap(StreamLogHandler.standardError)\n var log = Logger(label: \"com.apple.containerization\")\n log.logLevel = .debug\n return log\n}()\n\n@main\nstruct Application: AsyncParsableCommand {\n static let keychainID = \"com.apple.containerization\"\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.containerization\")\n }()\n\n private static let _contentStore: ContentStore = {\n try! LocalContentStore(path: appRoot.appendingPathComponent(\"content\"))\n }()\n\n private static let _imageStore: ImageStore = {\n try! ImageStore(\n path: appRoot,\n contentStore: contentStore\n )\n }()\n\n static var imageStore: ImageStore {\n _imageStore\n }\n\n static var contentStore: ContentStore {\n _contentStore\n }\n\n static let configuration = CommandConfiguration(\n commandName: \"cctl\",\n abstract: \"Utility CLI for Containerization\",\n version: \"2.0.0\",\n subcommands: [\n Images.self,\n Login.self,\n Rootfs.self,\n Run.self,\n ]\n )\n}\n\nextension String {\n var absoluteURL: URL {\n URL(fileURLWithPath: self).absoluteURL\n }\n}\n\nextension String: Swift.Error {\n\n}\n"], ["/containerization/Sources/ContainerizationOS/User.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\n\n/// `User` provides utilities to ensure that a given username exists in\n/// /etc/passwd (and /etc/group).\npublic enum User {\n private static let passwdFile = \"/etc/passwd\"\n private static let groupFile = \"/etc/group\"\n\n public struct ExecUser: Sendable {\n public var uid: UInt32\n public var gid: UInt32\n public var sgids: [UInt32]\n public var home: String\n }\n\n private struct User {\n let name: String\n let password: String\n let uid: UInt32\n let gid: UInt32\n let gecos: String\n let home: String\n let shell: String\n\n /// The argument `rawString` must follow the below format.\n /// Name:Password:Uid:Gid:Gecos:Home:Shell\n init(rawString: String) throws {\n let args = rawString.split(separator: \":\", omittingEmptySubsequences: false)\n guard args.count == 7 else {\n throw ContainerizationError.init(.invalidArgument, message: \"Cannot parse User from '\\(rawString)'\")\n }\n guard let uid = UInt32(args[2]) else {\n throw ContainerizationError.init(.invalidArgument, message: \"Cannot parse uid from '\\(args[2])'\")\n }\n guard let gid = UInt32(args[3]) else {\n throw ContainerizationError.init(.invalidArgument, message: \"Cannot parse gid from '\\(args[3])'\")\n }\n self.name = String(args[0])\n self.password = String(args[1])\n self.uid = uid\n self.gid = gid\n self.gecos = String(args[4])\n self.home = String(args[5])\n self.shell = String(args[6])\n }\n }\n\n private struct Group {\n let name: String\n let password: String\n let gid: UInt32\n let users: [String]\n\n /// The argument `rawString` must follow the below format.\n /// Name:Password:Gid:user1,user2\n init(rawString: String) throws {\n let args = rawString.split(separator: \":\", omittingEmptySubsequences: false)\n guard args.count == 4 else {\n throw ContainerizationError.init(.invalidArgument, message: \"Cannot parse Group from '\\(rawString)'\")\n }\n guard let gid = UInt32(args[2]) else {\n throw ContainerizationError.init(.invalidArgument, message: \"Cannot parse gid from '\\(args[2])'\")\n }\n self.name = String(args[0])\n self.password = String(args[1])\n self.gid = gid\n self.users = args[3].split(separator: \",\").map { String($0) }\n }\n }\n}\n\n// MARK: Private methods\n\nextension User {\n /// Parse the contents of the passwd file\n private static func parsePasswd(passwdFile: URL) throws -> [User] {\n var users: [User] = []\n try self.parse(file: passwdFile) { line in\n let user = try User(rawString: line)\n users.append(user)\n }\n return users\n }\n\n /// Parse the contents of the group file\n private static func parseGroup(groupFile: URL) throws -> [Group] {\n var groups: [Group] = []\n try self.parse(file: groupFile) { line in\n let group = try Group(rawString: line)\n groups.append(group)\n }\n return groups\n }\n\n private static func parse(file: URL, handler: (_ line: String) throws -> Void) throws {\n let fm = FileManager.default\n guard fm.fileExists(atPath: file.absolutePath()) else {\n throw ContainerizationError(.notFound, message: \"File \\(file.absolutePath()) does not exist\")\n }\n let content = try String(contentsOf: file, encoding: .ascii)\n let lines = content.components(separatedBy: .newlines)\n for line in lines {\n guard !line.isEmpty else {\n continue\n }\n try handler(line.trimmingCharacters(in: .whitespaces))\n }\n }\n}\n\n// MARK: Public methods\n\nextension User {\n public static func parseUser(root: String, userString: String) throws -> ExecUser {\n let defaultUser = ExecUser(uid: 0, gid: 0, sgids: [], home: \"/\")\n guard !userString.isEmpty else {\n return defaultUser\n }\n\n let passwdPath = URL(filePath: root).appending(path: Self.passwdFile)\n let groupPath = URL(filePath: root).appending(path: Self.groupFile)\n let parts = userString.split(separator: \":\", maxSplits: 1, omittingEmptySubsequences: false)\n\n let userArg = String(parts[0])\n let userIdArg = Int(userArg)\n\n guard FileManager.default.fileExists(atPath: passwdPath.absolutePath()) else {\n guard let userIdArg else {\n throw ContainerizationError(.internalError, message: \"Cannot parse username \\(userArg)\")\n }\n let uid = UInt32(userIdArg)\n guard parts.count > 1 else {\n return ExecUser(uid: uid, gid: uid, sgids: [], home: \"/\")\n }\n guard let gid = UInt32(String(parts[1])) else {\n throw ContainerizationError(.internalError, message: \"Cannot parse user group from \\(userString)\")\n }\n return ExecUser(uid: uid, gid: gid, sgids: [], home: \"/\")\n }\n\n let registeredUsers = try parsePasswd(passwdFile: passwdPath)\n guard registeredUsers.count > 0 else {\n throw ContainerizationError(.internalError, message: \"No users configured in passwd file.\")\n }\n let matches = registeredUsers.filter { registeredUser in\n // Check for a match (either uid/name) against the configured users from the passwd file.\n // We have to check both the uid and the name cause we dont know the type of `userString`\n registeredUser.name == userArg || registeredUser.uid == (userIdArg ?? -1)\n }\n guard let match = matches.first else {\n // We did not find a matching uid/username in the passwd file\n throw ContainerizationError(.internalError, message: \"Cannot find User '\\(userArg)' in passwd file.\")\n }\n\n var user = ExecUser(uid: match.uid, gid: match.gid, sgids: [match.gid], home: match.home)\n\n guard !match.name.isEmpty else {\n return user\n }\n let matchedUser = match.name\n var groupArg = \"\"\n var groupIdArg: Int? = nil\n if parts.count > 1 {\n groupArg = String(parts[1])\n groupIdArg = Int(groupArg)\n }\n\n let registeredGroups: [Group] = {\n do {\n // Parse the /etc/group file for a list of registered groups.\n // If the file is missing / malformed, we bail out\n return try parseGroup(groupFile: groupPath)\n } catch {\n return []\n }\n }()\n guard registeredGroups.count > 0 else {\n return user\n }\n let matchingGroups = registeredGroups.filter { registeredGroup in\n if !groupArg.isEmpty {\n return registeredGroup.gid == (groupIdArg ?? -1) || registeredGroup.name == groupArg\n }\n return registeredGroup.users.contains(matchedUser) || registeredGroup.gid == match.gid\n }\n guard matchingGroups.count > 0 else {\n throw ContainerizationError(.internalError, message: \"Cannot find Group '\\(groupArg)' in groups file.\")\n }\n // We have found a list of groups that match the group specified in the argument `userString`.\n // Set the matched groups as the supplement groups for the user\n if !groupArg.isEmpty {\n // Reassign the user's group only we were explicitly asked for a group\n user.gid = matchingGroups.first!.gid\n user.sgids = matchingGroups.map { group in\n group.gid\n }\n } else {\n user.sgids.append(\n contentsOf: matchingGroups.map { group in\n group.gid\n })\n }\n return user\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/ArchiveWriter.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CArchive\nimport Foundation\n\n/// A class responsible for writing archives in various formats.\npublic final class ArchiveWriter {\n var underlying: OpaquePointer!\n var delegate: FileArchiveWriterDelegate?\n\n /// Initialize a new `ArchiveWriter` with the given configuration.\n /// This method attempts to initialize an empty archive in memory, failing which it throws a `unableToCreateArchive` error.\n public init(configuration: ArchiveWriterConfiguration) throws {\n // because for some bizarre reason, UTF8 paths won't work unless this process explicitly sets a locale like en_US.UTF-8\n try Self.attemptSetLocales(locales: configuration.locales)\n\n guard let underlying = archive_write_new() else { throw ArchiveError.unableToCreateArchive }\n self.underlying = underlying\n\n try setFormat(configuration.format)\n try addFilter(configuration.filter)\n try setOptions(configuration.options)\n }\n\n /// Initialize a new `ArchiveWriter` with the given configuration and specified delegate.\n private convenience init(configuration: ArchiveWriterConfiguration, delegate: FileArchiveWriterDelegate) throws {\n try self.init(configuration: configuration)\n self.delegate = delegate\n try self.open()\n }\n\n private convenience init(configuration: ArchiveWriterConfiguration, file: URL) throws {\n try self.init(configuration: configuration, delegate: FileArchiveWriterDelegate(url: file))\n }\n\n /// Initialize a new `ArchiveWriter` for writing into the specified file with the given configuration options.\n public convenience init(format: Format, filter: Filter, options: [Options] = [], file: URL) throws {\n try self.init(\n configuration: .init(format: format, filter: filter), delegate: FileArchiveWriterDelegate(url: file))\n }\n\n /// Opens the given file for writing data into\n public func open(file: URL) throws {\n guard let underlying = underlying else { throw ArchiveError.noUnderlyingArchive }\n let res = archive_write_open_filename(underlying, file.path)\n try wrap(res, ArchiveError.unableToOpenArchive, underlying: underlying)\n }\n\n /// Opens the given fd for writing data into\n public func open(fileDescriptor: Int32) throws {\n guard let underlying = underlying else { throw ArchiveError.noUnderlyingArchive }\n let res = archive_write_open_fd(underlying, fileDescriptor)\n try wrap(res, ArchiveError.unableToOpenArchive, underlying: underlying)\n }\n\n /// Performs any necessary finalizations on the archive and releases resources.\n public func finishEncoding() throws {\n if let u = underlying {\n let r = archive_free(u)\n do {\n try wrap(r, ArchiveError.unableToCloseArchive, underlying: underlying)\n underlying = nil\n } catch {\n underlying = nil\n throw error\n }\n }\n }\n\n deinit {\n if let u = underlying {\n archive_free(u)\n underlying = nil\n }\n }\n\n private static func attemptSetLocales(locales: [String]) throws {\n for locale in locales {\n if setlocale(LC_ALL, locale) != nil {\n return\n }\n }\n throw ArchiveError.failedToSetLocale(locales: locales)\n }\n}\n\nextension ArchiveWriter {\n fileprivate func open() throws {\n guard let underlying = underlying else { throw ArchiveError.noUnderlyingArchive }\n // TODO: to be or not to be retained, that is the question\n let pointerToSelf = Unmanaged.passUnretained(self).toOpaque()\n\n let res = archive_write_open2(\n underlying,\n pointerToSelf,\n /// The open callback is invoked by archive_write_open(). It should return ARCHIVE_OK if the underlying file or data source is successfully opened. If the open fails, it should call archive_set_error() to register an error code and message and return ARCHIVE_FATAL. Please note that\n /// if open fails, close is not called and resources must be freed inside the open callback or with the free callback.\n { underlying, pointerToSelf in\n do {\n guard let pointerToSelf = pointerToSelf else {\n throw ArchiveError.noArchiveInCallback\n }\n let archive: ArchiveWriter = Unmanaged.fromOpaque(pointerToSelf).takeUnretainedValue()\n guard let delegate = archive.delegate else {\n throw ArchiveError.noDelegateConfigured\n }\n try delegate.open(archive: archive)\n return ARCHIVE_OK\n } catch {\n archive_set_error_wrapper(underlying, ARCHIVE_FATAL, \"\\(error)\")\n return ARCHIVE_FATAL\n }\n },\n /// The write callback is invoked whenever the library needs to write raw bytes to the archive. For correct blocking, each call to the write callback function should translate into a single write(2) system call. This is especially critical when writing archives to tape drives. On\n /// success, the write callback should return the number of bytes actually written. On error, the callback should invoke archive_set_error() to register an error code and message and return -1.\n { underlying, pointerToSelf, dataPointer, count in\n do {\n guard let pointerToSelf = pointerToSelf else {\n throw ArchiveError.noArchiveInCallback\n }\n let archive: ArchiveWriter = Unmanaged.fromOpaque(pointerToSelf).takeUnretainedValue()\n guard let delegate = archive.delegate else {\n throw ArchiveError.noDelegateConfigured\n }\n return try delegate.write(\n archive: archive, buffer: UnsafeRawBufferPointer(start: dataPointer, count: count))\n } catch {\n archive_set_error_wrapper(underlying, ARCHIVE_FATAL, \"\\(error)\")\n return -1\n }\n },\n /// The close callback is invoked by archive_close when the archive processing is complete. If the open callback fails, the close callback is not invoked. The callback should return ARCHIVE_OK on success. On failure, the callback should invoke archive_set_error() to register an\n /// error code and message and return\n { underlying, pointerToSelf in\n do {\n guard let pointerToSelf = pointerToSelf else {\n throw ArchiveError.noArchiveInCallback\n }\n let archive: ArchiveWriter = Unmanaged.fromOpaque(pointerToSelf).takeUnretainedValue()\n guard let delegate = archive.delegate else {\n throw ArchiveError.noDelegateConfigured\n }\n try delegate.close(archive: archive)\n return ARCHIVE_OK\n } catch {\n archive_set_error_wrapper(underlying, ARCHIVE_FATAL, \"\\(error)\")\n return ARCHIVE_FATAL\n }\n },\n /// The free callback is always invoked on archive_free. The return code of this callback is not processed.\n { underlying, pointerToSelf in\n do {\n guard let pointerToSelf = pointerToSelf else {\n throw ArchiveError.noArchiveInCallback\n }\n let archive: ArchiveWriter = Unmanaged.fromOpaque(pointerToSelf).takeUnretainedValue()\n guard let delegate = archive.delegate else {\n throw ArchiveError.noDelegateConfigured\n }\n delegate.free(archive: archive)\n\n // TODO: should we balance the Unmanaged refcount here? Need to test for leaks.\n return ARCHIVE_OK\n } catch {\n archive_set_error_wrapper(underlying, ARCHIVE_FATAL, \"\\(error)\")\n return ARCHIVE_FATAL\n }\n }\n )\n\n try wrap(res, ArchiveError.unableToOpenArchive, underlying: underlying)\n }\n}\n\npublic class ArchiveWriterTransaction {\n private let writer: ArchiveWriter\n\n fileprivate init(writer: ArchiveWriter) {\n self.writer = writer\n }\n\n public func writeHeader(entry: WriteEntry) throws {\n try writer.writeHeader(entry: entry)\n }\n\n public func writeChunk(data: UnsafeRawBufferPointer) throws {\n try writer.writeData(data: data)\n }\n\n public func finish() throws {\n try writer.finishEntry()\n }\n}\n\nextension ArchiveWriter {\n public func makeTransactionWriter() -> ArchiveWriterTransaction {\n ArchiveWriterTransaction(writer: self)\n }\n\n /// Create a new entry in the archive with the given properties.\n /// - Parameters:\n /// - entry: A `WriteEntry` object describing the metadata of the entry to be created\n /// (e.g., name, modification date, permissions).\n /// - data: The `Data` object containing the content for the new entry.\n public func writeEntry(entry: WriteEntry, data: Data) throws {\n try data.withUnsafeBytes { bytes in\n try writeEntry(entry: entry, data: bytes)\n }\n }\n\n /// Creates a new entry in the archive with the given properties.\n ///\n /// This method performs the following:\n /// 1. Writes the archive header using the provided `WriteEntry` metadata.\n /// 2. Writes the content from the `UnsafeRawBufferPointer` into the archive.\n /// 3. Finalizes the entry in the archive.\n ///\n /// - Parameters:\n /// - entry: A `WriteEntry` object describing the metadata of the entry to be created\n /// (e.g., name, modification date, permissions, type).\n /// - data: An optional `UnsafeRawBufferPointer` containing the raw bytes for the new entry's\n /// content. Pass `nil` for entries that do not have content data (e.g., directories, symlinks).\n public func writeEntry(entry: WriteEntry, data: UnsafeRawBufferPointer?) throws {\n try writeHeader(entry: entry)\n if let data = data {\n try writeData(data: data)\n }\n try finishEntry()\n }\n\n fileprivate func writeHeader(entry: WriteEntry) throws {\n guard let underlying = self.underlying else { throw ArchiveError.noUnderlyingArchive }\n\n try wrap(\n archive_write_header(underlying, entry.underlying), ArchiveError.unableToWriteEntryHeader,\n underlying: underlying)\n }\n\n fileprivate func finishEntry() throws {\n guard let underlying = self.underlying else { throw ArchiveError.noUnderlyingArchive }\n\n archive_write_finish_entry(underlying)\n }\n\n fileprivate func writeData(data: UnsafeRawBufferPointer) throws {\n guard let underlying = self.underlying else { throw ArchiveError.noUnderlyingArchive }\n\n let result = archive_write_data(underlying, data.baseAddress, data.count)\n guard result >= 0 else {\n throw ArchiveError.unableToWriteData(result)\n }\n }\n}\n\nextension ArchiveWriter {\n /// Recursively archives the content of a directory. Regular files, symlinks and directories are added into the archive.\n /// Note: Symlinks are added to the archive if both the source and target for the symlink are both contained in the top level directory.\n public func archiveDirectory(_ dir: URL) throws {\n let fm = FileManager.default\n let resourceKeys = Set([\n .fileSizeKey, .fileResourceTypeKey,\n .creationDateKey, .contentAccessDateKey, .contentModificationDateKey, .fileSecurityKey,\n ])\n guard let directoryEnumerator = fm.enumerator(at: dir, includingPropertiesForKeys: Array(resourceKeys), options: .producesRelativePathURLs) else {\n throw POSIXError(.ENOTDIR)\n }\n for case let fileURL as URL in directoryEnumerator {\n var mode = mode_t()\n var uid = uid_t()\n var gid = gid_t()\n let resourceValues = try fileURL.resourceValues(forKeys: resourceKeys)\n guard let type = resourceValues.fileResourceType else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .fileResourceTypeKey)\n }\n let allowedTypes: [URLFileResourceType] = [.directory, .regular, .symbolicLink]\n guard allowedTypes.contains(type) else {\n continue\n }\n var size: Int64 = 0\n let entry = WriteEntry()\n if type == .regular {\n guard let _size = resourceValues.fileSize else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .fileSizeKey)\n }\n size = Int64(_size)\n } else if type == .symbolicLink {\n let target = fileURL.resolvingSymlinksInPath().absoluteString\n let root = dir.absoluteString\n guard target.hasPrefix(root) else {\n continue\n }\n let linkTarget = target.dropFirst(root.count + 1)\n entry.symlinkTarget = String(linkTarget)\n }\n\n guard let created = resourceValues.creationDate else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .creationDateKey)\n }\n guard let access = resourceValues.contentAccessDate else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .contentAccessDateKey)\n }\n guard let modified = resourceValues.contentModificationDate else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .contentModificationDateKey)\n }\n guard let perms = resourceValues.fileSecurity else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .fileSecurityKey)\n }\n CFFileSecurityGetMode(perms, &mode)\n CFFileSecurityGetOwner(perms, &uid)\n CFFileSecurityGetGroup(perms, &gid)\n entry.path = fileURL.relativePath\n entry.size = size\n entry.creationDate = created\n entry.modificationDate = modified\n entry.contentAccessDate = access\n entry.fileType = type\n entry.group = gid\n entry.owner = uid\n entry.permissions = mode\n if type == .regular {\n let p = dir.appending(path: fileURL.relativePath)\n let data = try Data(contentsOf: p, options: .uncached)\n try self.writeEntry(entry: entry, data: data)\n } else {\n try self.writeHeader(entry: entry)\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Reader.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\nextension EXT4 {\n /// The `EXT4Reader` opens a block device, parses the superblock, and loads group descriptors & inodes.\n public class EXT4Reader {\n public var superBlock: EXT4.SuperBlock {\n self._superBlock\n }\n\n let handle: FileHandle\n let _superBlock: EXT4.SuperBlock\n\n private var groupDescriptors: [UInt32: EXT4.GroupDescriptor] = [:]\n private var inodes: [InodeNumber: EXT4.Inode] = [:]\n\n var hardlinks: [FilePath: InodeNumber] = [:]\n var tree: EXT4.FileTree = EXT4.FileTree(EXT4.RootInode, \".\")\n var blockSize: UInt64 {\n UInt64(1024 * (1 << _superBlock.logBlockSize))\n }\n\n private var groupDescriptorSize: UInt16 {\n if _superBlock.featureIncompat & EXT4.IncompatFeature.bit64.rawValue != 0 {\n return _superBlock.descSize\n }\n return UInt16(MemoryLayout.size)\n }\n\n public init(blockDevice: FilePath) throws {\n guard FileManager.default.fileExists(atPath: blockDevice.description) else {\n throw EXT4.Error.notFound(blockDevice.description)\n }\n\n guard let fileHandle = FileHandle(forReadingAtPath: blockDevice) else {\n throw Error.notFound(blockDevice.description)\n }\n self.handle = fileHandle\n try handle.seek(toOffset: EXT4.SuperBlockOffset)\n\n let superBlockSize = MemoryLayout.size\n guard let data = try? self.handle.read(upToCount: superBlockSize) else {\n throw EXT4.Error.couldNotReadSuperBlock(blockDevice.description, EXT4.SuperBlockOffset, superBlockSize)\n }\n let sb = data.withUnsafeBytes { ptr in\n ptr.loadLittleEndian(as: EXT4.SuperBlock.self)\n }\n guard sb.magic == EXT4.SuperBlockMagic else {\n throw EXT4.Error.invalidSuperBlock\n }\n self._superBlock = sb\n var items: [(item: Ptr, inode: InodeNumber)] = [\n (self.tree.root, EXT4.RootInode)\n ]\n while items.count > 0 {\n guard let item = items.popLast() else {\n break\n }\n let (itemPtr, inodeNum) = item\n let childItems = try self.children(of: inodeNum)\n let root = itemPtr.pointee\n for (itemName, itemInodeNum) in childItems {\n if itemName == \".\" || itemName == \"..\" {\n continue\n }\n\n if self.inodes[itemInodeNum] != nil {\n // we have seen this inode before, we will hard link this file to it\n guard let parentPath = itemPtr.pointee.path else {\n continue\n }\n let path = parentPath.join(itemName)\n self.hardlinks[path] = itemInodeNum\n continue\n }\n\n let blocks = try self.getExtents(inode: itemInodeNum)\n let itemTreeNodePtr = Ptr.allocate(capacity: 1)\n let itemTreeNode = FileTree.FileTreeNode(\n inode: itemInodeNum,\n name: itemName,\n parent: itemPtr,\n children: []\n )\n if let blocks {\n if blocks.count > 1 {\n itemTreeNode.additionalBlocks = Array(blocks.dropFirst())\n }\n itemTreeNode.blocks = blocks.first\n }\n itemTreeNodePtr.initialize(to: itemTreeNode)\n root.children.append(itemTreeNodePtr)\n itemPtr.initialize(to: root)\n let itemInode = try self.getInode(number: itemInodeNum)\n if itemInode.mode.isDir() {\n items.append((itemTreeNodePtr, itemInodeNum))\n }\n }\n }\n }\n\n deinit {\n try? self.handle.close()\n }\n\n private func readGroupDescriptor(_ number: UInt32) throws -> GroupDescriptor {\n let bs = UInt64(1024 * (1 << _superBlock.logBlockSize))\n let offset = bs + UInt64(number) * UInt64(self.groupDescriptorSize)\n try self.handle.seek(toOffset: offset)\n guard let data = try? self.handle.read(upToCount: MemoryLayout.size) else {\n throw EXT4.Error.couldNotReadGroup(number)\n }\n let gd = data.withUnsafeBytes { ptr in\n ptr.loadLittleEndian(as: EXT4.GroupDescriptor.self)\n }\n return gd\n }\n\n private func readInode(_ number: UInt32) throws -> Inode {\n let inodeGroupNumber = ((number - 1) / self._superBlock.inodesPerGroup)\n let numberInGroup = UInt64((number - 1) % self._superBlock.inodesPerGroup)\n\n let gd = try getGroupDescriptor(inodeGroupNumber)\n let inodeTableStart = UInt64(gd.inodeTableLow) * self.blockSize\n\n let inodeOffset: UInt64 = inodeTableStart + numberInGroup * UInt64(_superBlock.inodeSize)\n try self.handle.seek(toOffset: inodeOffset)\n guard let inodeData = try self.handle.read(upToCount: MemoryLayout.size) else {\n throw EXT4.Error.couldNotReadInode(number)\n }\n let inode = inodeData.withUnsafeBytes { ptr in\n ptr.loadLittleEndian(as: EXT4.Inode.self)\n }\n return inode\n }\n\n private func getDirTree(_ number: InodeNumber) throws -> [(String, InodeNumber)] {\n var children: [(String, InodeNumber)] = []\n let extents = try getExtents(inode: number) ?? []\n for (start, end) in extents {\n try self.seek(block: start)\n for i in 0..<(end - start) {\n guard let dirEntryBlock = try self.handle.read(upToCount: Int(self.blockSize)) else {\n throw EXT4.Error.couldNotReadBlock(start + i)\n }\n let childEntries = try getDirEntries(dirTree: dirEntryBlock)\n children.append(contentsOf: childEntries)\n }\n }\n return children.sorted { a, b in\n a.0 < b.0\n }\n }\n\n private func getDirEntries(dirTree: Data) throws -> [(String, InodeNumber)] {\n var children: [(String, InodeNumber)] = []\n var offset = 0\n while offset < dirTree.count {\n let length = MemoryLayout.size\n let dirEntry = dirTree.subdata(in: offset.. [(start: UInt32, end: UInt32)]? {\n let inode = try self.getInode(number: inode)\n let inodeBlock = Data(tupleToArray(inode.block))\n var offset = 0\n var extents: [(start: UInt32, end: UInt32)] = []\n\n let extentHeaderSize = MemoryLayout.size\n let extentIndexSize = MemoryLayout.size\n let extentLeafSize = MemoryLayout.size\n // read extent header\n let header = inodeBlock.subdata(in: offset.. Inode {\n if let inode = self.inodes[number] {\n return inode\n }\n\n let inode = try readInode(number)\n self.inodes[number] = inode\n return inode\n }\n\n func getGroupDescriptor(_ number: UInt32) throws -> GroupDescriptor {\n if let gd = self.groupDescriptors[number] {\n return gd\n }\n let gd = try readGroupDescriptor(number)\n self.groupDescriptors[number] = gd\n return gd\n }\n\n func children(of number: EXT4.InodeNumber) throws -> [(String, InodeNumber)] {\n try getDirTree(number)\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Command.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CShim\nimport Foundation\nimport Synchronization\n\n#if canImport(Darwin)\nimport Darwin\nprivate let _kill = Darwin.kill\n#elseif canImport(Musl)\nimport Musl\nprivate let _kill = Musl.kill\n#elseif canImport(Glibc)\nimport Glibc\nprivate let _kill = Glibc.kill\n#endif\n\n/// Use a command to run an executable.\npublic struct Command: Sendable {\n /// Path to the executable binary.\n public var executable: String\n /// Arguments provided to the binary.\n public var arguments: [String]\n /// Environment variables for the process.\n public var environment: [String]\n /// The directory where the process should execute.\n public var directory: String?\n /// Additional files to pass to the process.\n public var extraFiles: [FileHandle]\n /// The standard input.\n public var stdin: FileHandle?\n /// The standard output.\n public var stdout: FileHandle?\n /// The standard error.\n public var stderr: FileHandle?\n\n private let state: State\n\n /// System level attributes to set on the process.\n public struct Attrs: Sendable {\n /// Set pgroup for the new process.\n public var setPGroup: Bool\n /// Inherit the real uid/gid of the parent.\n public var resetIDs: Bool\n /// Reset the child's signal handlers to the default.\n public var setSignalDefault: Bool\n /// The initial signal mask for the process.\n public var signalMask: UInt32\n /// Create a new session for the process.\n public var setsid: Bool\n /// Set the controlling terminal for the process to fd 0.\n public var setctty: Bool\n /// Set the process user ID.\n public var uid: UInt32?\n /// Set the process group ID.\n public var gid: UInt32?\n\n public init(\n setPGroup: Bool = false,\n resetIDs: Bool = false,\n setSignalDefault: Bool = true,\n signalMask: UInt32 = 0,\n setsid: Bool = false,\n setctty: Bool = false,\n uid: UInt32? = nil,\n gid: UInt32? = nil\n ) {\n self.setPGroup = setPGroup\n self.resetIDs = resetIDs\n self.setSignalDefault = setSignalDefault\n self.signalMask = signalMask\n self.setsid = setsid\n self.setctty = setctty\n self.uid = uid\n self.gid = gid\n }\n }\n\n private final class State: Sendable {\n let pid: Atomic = Atomic(-1)\n }\n\n /// Attributes to set on the process.\n public var attrs = Attrs()\n\n /// System level process identifier.\n public var pid: Int32 { self.state.pid.load(ordering: .acquiring) }\n\n public init(\n _ executable: String,\n arguments: [String] = [],\n environment: [String] = environment(),\n directory: String? = nil,\n extraFiles: [FileHandle] = []\n ) {\n self.executable = executable\n self.arguments = arguments\n self.environment = environment\n self.extraFiles = extraFiles\n self.directory = directory\n self.state = State()\n }\n\n public static func environment() -> [String] {\n ProcessInfo.processInfo.environment\n .map { \"\\($0)=\\($1)\" }\n }\n}\n\nextension Command {\n public enum Error: Swift.Error, CustomStringConvertible {\n case processRunning\n\n public var description: String {\n switch self {\n case .processRunning:\n return \"the process is already running\"\n }\n }\n }\n}\n\nextension Command {\n @discardableResult\n public func kill(_ signal: Int32) -> Int32? {\n let pid = self.pid\n guard pid > 0 else {\n return nil\n }\n return _kill(pid, signal)\n }\n}\n\nextension Command {\n /// Start the process.\n public func start() throws {\n guard self.pid == -1 else {\n throw Error.processRunning\n }\n let child = try execute()\n self.state.pid.store(child, ordering: .releasing)\n }\n\n /// Wait for the process to exit and return the exit status.\n @discardableResult\n public func wait() throws -> Int32 {\n var rus = rusage()\n var ws = Int32()\n\n let pid = self.pid\n guard pid > 0 else {\n return -1\n }\n\n let result = wait4(pid, &ws, 0, &rus)\n guard result == pid else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n return Self.toExitStatus(ws)\n }\n\n private func execute() throws -> pid_t {\n var attrs = exec_command_attrs()\n exec_command_attrs_init(&attrs)\n\n let set = try createFileset()\n defer {\n try? set.null.close()\n }\n var fds = [Int32](repeating: 0, count: set.handles.count)\n for (i, handle) in set.handles.enumerated() {\n fds[i] = handle.fileDescriptor\n }\n\n attrs.setsid = self.attrs.setsid ? 1 : 0\n attrs.setctty = self.attrs.setctty ? 1 : 0\n attrs.setpgid = self.attrs.setPGroup ? 1 : 0\n\n var cwdPath: UnsafeMutablePointer?\n if let chdir = self.directory {\n cwdPath = strdup(chdir)\n }\n defer {\n if let cwdPath {\n free(cwdPath)\n }\n }\n\n if let uid = self.attrs.uid {\n attrs.uid = uid\n }\n if let gid = self.attrs.gid {\n attrs.gid = gid\n }\n\n var pid: pid_t = 0\n var argv = ([executable] + arguments).map { strdup($0) } + [nil]\n defer {\n for arg in argv where arg != nil {\n free(arg)\n }\n }\n\n let env = environment.map { strdup($0) } + [nil]\n defer {\n for e in env where e != nil {\n free(e)\n }\n }\n\n let result = fds.withUnsafeBufferPointer { file_handles in\n exec_command(\n &pid,\n argv[0],\n &argv,\n env,\n file_handles.baseAddress!, Int32(file_handles.count),\n cwdPath ?? nil,\n &attrs)\n }\n guard result == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n\n return pid\n }\n\n /// Create a posix_spawn file actions set of fds to pass to the new process\n private func createFileset() throws -> (null: FileHandle, handles: [FileHandle]) {\n // grab dev null incase a handle passed by the user is nil\n let null = try openDevNull()\n var files = [FileHandle]()\n files.append(stdin ?? null)\n files.append(stdout ?? null)\n files.append(stderr ?? null)\n files.append(contentsOf: extraFiles)\n return (null: null, handles: files)\n }\n\n /// Returns a file handle to /dev/null.\n private func openDevNull() throws -> FileHandle {\n let fd = open(\"/dev/null\", O_WRONLY, 0)\n guard fd > 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n return FileHandle(fileDescriptor: fd, closeOnDealloc: false)\n }\n}\n\nextension Command {\n private static let signalOffset: Int32 = 128\n\n private static let shift: Int32 = 8\n private static let mask: Int32 = 0x7F\n private static let stopped: Int32 = 0x7F\n private static let exited: Int32 = 0x00\n\n static func signaled(_ ws: Int32) -> Bool {\n ws & mask != stopped && ws & mask != exited\n }\n\n static func exited(_ ws: Int32) -> Bool {\n ws & mask == exited\n }\n\n static func exitStatus(_ ws: Int32) -> Int32 {\n let r: Int32\n #if os(Linux)\n r = ws >> shift & 0xFF\n #else\n r = ws >> shift\n #endif\n return r\n }\n\n public static func toExitStatus(_ ws: Int32) -> Int32 {\n if signaled(ws) {\n // We use the offset as that is how existing container\n // runtimes minic bash for the status when signaled.\n return Int32(Self.signalOffset + ws & mask)\n }\n if exited(ws) {\n return exitStatus(ws)\n }\n return ws\n }\n\n}\n\nprivate func WIFEXITED(_ status: Int32) -> Bool {\n _WSTATUS(status) == 0\n}\n\nprivate func _WSTATUS(_ status: Int32) -> Int32 {\n status & 0x7f\n}\n\nprivate func WIFSIGNALED(_ status: Int32) -> Bool {\n (_WSTATUS(status) != 0) && (_WSTATUS(status) != 0x7f)\n}\n\nprivate func WEXITSTATUS(_ status: Int32) -> Int32 {\n (status >> 8) & 0xff\n}\n\nprivate func WTERMSIG(_ status: Int32) -> Int32 {\n status & 0x7f\n}\n"], ["/containerization/vminitd/Sources/vmexec/vmexec.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// NOTE: This binary implements a very small subset of the OCI runtime spec, mostly just\n/// the process configurations. Mounts are somewhat functional, but masked and read only paths\n/// aren't checked today. Today the namespaces are also ignored, and we always spawn a new pid\n/// and mount namespace.\n\nimport ArgumentParser\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport LCShim\nimport Logging\nimport Musl\n\n@main\nstruct App: ParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"vmexec\",\n version: \"0.1.0\",\n subcommands: [\n ExecCommand.self,\n RunCommand.self,\n ]\n )\n\n static let standardErrorLock = NSLock()\n\n @Sendable\n static func standardError(label: String) -> StreamLogHandler {\n standardErrorLock.withLock {\n StreamLogHandler.standardError(label: label)\n }\n }\n}\n\nextension App {\n /// Applies O_CLOEXEC to all file descriptors currently open for\n /// the process except the stdio fd values\n static func applyCloseExecOnFDs() throws {\n let minFD = 2 // stdin, stdout, stderr should be preserved\n\n let fdList = try FileManager.default.contentsOfDirectory(atPath: \"/proc/self/fd\")\n\n for fdStr in fdList {\n guard let fd = Int(fdStr) else {\n continue\n }\n if fd <= minFD {\n continue\n }\n\n _ = fcntl(Int32(fd), F_SETFD, FD_CLOEXEC)\n }\n }\n\n static func exec(process: ContainerizationOCI.Process) throws {\n let executable = strdup(process.args[0])\n var argv = process.args.map { strdup($0) }\n argv += [nil]\n\n let env = process.env.map { strdup($0) } + [nil]\n let cwd = process.cwd\n\n // switch cwd\n guard chdir(cwd) == 0 else {\n throw App.Errno(stage: \"chdir(cwd)\", info: \"Failed to change directory to '\\(cwd)'\")\n }\n\n guard execvpe(executable, argv, env) != -1 else {\n throw App.Errno(stage: \"execvpe(\\(String(describing: executable)))\", info: \"Failed to exec [\\(process.args.joined(separator: \" \"))]\")\n }\n fatalError(\"execvpe failed\")\n }\n\n static func setPermissions(user: ContainerizationOCI.User) throws {\n if user.additionalGids.count > 0 {\n guard setgroups(user.additionalGids.count, user.additionalGids) == 0 else {\n throw App.Errno(stage: \"setgroups()\")\n }\n }\n guard setgid(user.gid) == 0 else {\n throw App.Errno(stage: \"setgid()\")\n }\n // NOTE: setuid has to be done last because once the uid has been\n // changed, then the process will lose privilege to set the group\n // and supplementary groups\n guard setuid(user.uid) == 0 else {\n throw App.Errno(stage: \"setuid()\")\n }\n }\n\n static func fixStdioPerms(user: ContainerizationOCI.User) throws {\n for i in 0...2 {\n var fdStat = stat()\n try withUnsafeMutablePointer(to: &fdStat) { pointer in\n guard fstat(Int32(i), pointer) == 0 else {\n throw App.Errno(stage: \"fstat(fd)\")\n }\n }\n\n let desired = uid_t(user.uid)\n if fdStat.st_uid != desired {\n guard fchown(Int32(i), desired, fdStat.st_gid) != -1 else {\n throw App.Errno(stage: \"fchown(\\(i))\")\n }\n }\n }\n }\n\n static func setRLimits(rlimits: [ContainerizationOCI.POSIXRlimit]) throws {\n for rl in rlimits {\n var limit = rlimit(rlim_cur: rl.soft, rlim_max: rl.hard)\n let resource: Int32\n switch rl.type {\n case \"RLIMIT_AS\":\n resource = RLIMIT_AS\n case \"RLIMIT_CORE\":\n resource = RLIMIT_CORE\n case \"RLIMIT_CPU\":\n resource = RLIMIT_CPU\n case \"RLIMIT_DATA\":\n resource = RLIMIT_DATA\n case \"RLIMIT_FSIZE\":\n resource = RLIMIT_FSIZE\n case \"RLIMIT_NOFILE\":\n resource = RLIMIT_NOFILE\n case \"RLIMIT_STACK\":\n resource = RLIMIT_STACK\n case \"RLIMIT_NPROC\":\n resource = RLIMIT_NPROC\n case \"RLIMIT_RSS\":\n resource = RLIMIT_RSS\n case \"RLIMIT_MEMLOCK\":\n resource = RLIMIT_MEMLOCK\n default:\n errno = EINVAL\n throw App.Errno(stage: \"rlimit key unknown\")\n }\n guard setrlimit(resource, &limit) == 0 else {\n throw App.Errno(stage: \"setrlimit()\")\n }\n }\n }\n\n static func Errno(stage: String, info: String = \"\") -> ContainerizationError {\n let posix = POSIXError(.init(rawValue: errno)!, userInfo: [\"stage\": stage])\n return ContainerizationError(.internalError, message: \"\\(info) \\(String(describing: posix))\")\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/RegistryClient+Token.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport ContainerizationError\nimport Foundation\n\nstruct TokenRequest {\n public static let authenticateHeaderName = \"WWW-Authenticate\"\n\n /// The credentials that will be used in the authentication header when fetching the token.\n let authentication: Authentication?\n /// The realm against which the token should be requested.\n let realm: String\n /// The name of the service which hosts the resource.\n let service: String\n /// Whether to return a refresh token along with the bearer token.\n let offlineToken: Bool\n /// String identifying the client.\n let clientId: String\n /// The resource in question, formatted as one of the space-delimited entries from the scope parameters from the WWW-Authenticate header shown above.\n let scope: String?\n\n init(\n realm: String,\n service: String,\n clientId: String,\n scope: String?,\n offlineToken: Bool = false,\n authentication: Authentication? = nil\n ) {\n self.realm = realm\n self.service = service\n self.offlineToken = offlineToken\n self.clientId = clientId\n self.scope = scope\n self.authentication = authentication\n }\n}\n\nstruct TokenResponse: Codable, Hashable {\n /// An opaque Bearer token that clients should supply to subsequent requests in the Authorization header.\n let token: String?\n /// For compatibility with OAuth 2.0, we will also accept token under the name access_token.\n /// At least one of these fields must be specified, but both may also appear (for compatibility with older clients).\n /// When both are specified, they should be equivalent; if they differ the client's choice is undefined.\n let accessToken: String?\n /// The duration in seconds since the token was issued that it will remain valid.\n /// When omitted, this defaults to 60 seconds.\n let expiresIn: UInt?\n /// The RFC3339-serialized UTC standard time at which a given token was issued.\n /// If issued_at is omitted, the expiration is from when the token exchange completed.\n let issuedAt: String?\n /// Token which can be used to get additional access tokens for the same subject with different scopes.\n /// This token should be kept secure by the client and only sent to the authorization server which issues bearer tokens.\n /// This field will only be set when `offline_token=true` is provided in the request.\n let refreshToken: String?\n\n var scope: String?\n\n private enum CodingKeys: String, CodingKey {\n case token = \"token\"\n case accessToken = \"access_token\"\n case expiresIn = \"expires_in\"\n case issuedAt = \"issued_at\"\n case refreshToken = \"refresh_token\"\n }\n\n func getToken() -> String? {\n if let t = token ?? accessToken {\n return \"Bearer \\(t)\"\n }\n return nil\n }\n\n func isValid(scope: String?) -> Bool {\n guard let issuedAt else {\n return false\n }\n let isoFormatter = ISO8601DateFormatter()\n isoFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]\n guard let issued = isoFormatter.date(from: issuedAt) else {\n return false\n }\n let expiresIn = expiresIn ?? 0\n let now = Date()\n let elapsed = now.timeIntervalSince(issued)\n guard elapsed < Double(expiresIn) else {\n return false\n }\n if let requiredScope = scope {\n return requiredScope == self.scope\n }\n return false\n }\n}\n\nstruct AuthenticateChallenge: Equatable {\n let type: String\n let realm: String?\n let service: String?\n let scope: String?\n let error: String?\n\n init(type: String, realm: String?, service: String?, scope: String?, error: String?) {\n self.type = type\n self.realm = realm\n self.service = service\n self.scope = scope\n self.error = error\n }\n\n init(type: String, values: [String: String]) {\n self.type = type\n self.realm = values[\"realm\"]\n self.service = values[\"service\"]\n self.scope = values[\"scope\"]\n self.error = values[\"error\"]\n }\n}\n\nextension RegistryClient {\n /// Fetch an auto token for all subsequent HTTP requests\n /// See https://docs.docker.com/registry/spec/auth/token/\n internal func fetchToken(request: TokenRequest) async throws -> TokenResponse {\n guard var components = URLComponents(string: request.realm) else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot create URL from \\(request.realm)\")\n }\n components.queryItems = [\n URLQueryItem(name: \"client_id\", value: request.clientId),\n URLQueryItem(name: \"service\", value: request.service),\n ]\n var scope = \"\"\n if let reqScope = request.scope {\n scope = reqScope\n components.queryItems?.append(URLQueryItem(name: \"scope\", value: reqScope))\n }\n\n if request.offlineToken {\n components.queryItems?.append(URLQueryItem(name: \"offline_token\", value: \"true\"))\n }\n var response: TokenResponse = try await requestJSON(components: components, headers: [])\n response.scope = scope\n return response\n }\n\n internal func createTokenRequest(parsing authenticateHeaders: [String]) throws -> TokenRequest {\n let parsedHeaders = Self.parseWWWAuthenticateHeaders(headers: authenticateHeaders)\n let bearerChallenge = parsedHeaders.first { $0.type == \"Bearer\" }\n guard let bearerChallenge else {\n throw ContainerizationError(.invalidArgument, message: \"Missing Bearer challenge in \\(TokenRequest.authenticateHeaderName) header\")\n }\n guard let realm = bearerChallenge.realm else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot parse realm from \\(TokenRequest.authenticateHeaderName) header\")\n }\n guard let service = bearerChallenge.service else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot parse service from \\(TokenRequest.authenticateHeaderName) header\")\n }\n let scope = bearerChallenge.scope\n let tokenRequest = TokenRequest(realm: realm, service: service, clientId: self.clientID, scope: scope, authentication: self.authentication)\n return tokenRequest\n }\n\n internal static func parseWWWAuthenticateHeaders(headers: [String]) -> [AuthenticateChallenge] {\n var parsed: [String: [String: String]] = [:]\n for challenge in headers {\n let trimmedChallenge = challenge.trimmingCharacters(in: .whitespacesAndNewlines)\n let parts = trimmedChallenge.split(separator: \" \", maxSplits: 1)\n guard parts.count == 2 else {\n continue\n }\n guard let scheme = parts.first else {\n continue\n }\n var params: [String: String] = [:]\n let header = String(parts[1])\n let pattern = #\"(\\w+)=\"([^\"]+)\"#\n let regex = try! NSRegularExpression(pattern: pattern, options: [])\n let matches = regex.matches(in: header, options: [], range: NSRange(header.startIndex..., in: header))\n for match in matches {\n if let keyRange = Range(match.range(at: 1), in: header),\n let valueRange = Range(match.range(at: 2), in: header)\n {\n let key = String(header[keyRange])\n let value = String(header[valueRange])\n params[key] = value\n }\n }\n parsed[String(scheme)] = params\n }\n var parsedChallenges: [AuthenticateChallenge] = []\n for (type, values) in parsed {\n parsedChallenges.append(.init(type: type, values: values))\n }\n return parsedChallenges\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Reference.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\n\nprivate let referenceTotalLengthMax = 255\nprivate let nameTotalLengthMax = 127\nprivate let legacyDockerRegistryHost = \"docker.io\"\nprivate let dockerRegistryHost = \"registry-1.docker.io\"\nprivate let defaultDockerRegistryRepo = \"library\"\nprivate let defaultTag = \"latest\"\n\n/// A Reference is composed of the various parts of an OCI image reference.\n/// For example:\n/// let imageReference = \"my-registry.com/repository/image:tag2\"\n/// let reference = Reference.parse(imageReference)\n/// print(reference.domain!) // gives us \"my-registry.com\"\n/// print(reference.name) // gives us \"my-registry.com/repository/image\"\n/// print(reference.path) // gives us \"repository/image\"\n/// print(reference.tag!) // gives us \"tag2\"\n/// print(reference.digest) // gives us \"nil\"\npublic class Reference: CustomStringConvertible {\n private var _domain: String?\n public var domain: String? {\n _domain\n }\n public var resolvedDomain: String? {\n if let d = _domain {\n return Self.resolveDomain(domain: d)\n }\n return nil\n }\n\n private var _path: String\n public var path: String {\n _path\n }\n\n private var _tag: String?\n public var tag: String? {\n _tag\n }\n\n private var _digest: String?\n public var digest: String? {\n _digest\n }\n\n public var name: String {\n if let domain, !domain.isEmpty {\n return \"\\(domain)/\\(path)\"\n }\n return path\n }\n\n public var description: String {\n if let tag {\n return \"\\(name):\\(tag)\"\n }\n if let digest {\n return \"\\(name)@\\(digest)\"\n }\n return name\n }\n\n static let identifierPattern = \"([a-f0-9]{64})\"\n\n static let domainPattern = {\n let domainNameComponent = \"(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])\"\n let optionalPort = \"(?::[0-9]+)?\"\n let ipv6address = \"\\\\[(?:[a-fA-F0-9:]+)\\\\]\"\n let domainName = \"\\(domainNameComponent)(?:\\\\.\\(domainNameComponent))*\"\n let host = \"(?:\\(domainName)|\\(ipv6address))\"\n let domainAndPort = \"\\(host)\\(optionalPort)\"\n return domainAndPort\n }()\n\n static let pathPattern = \"(?(?:[a-z0-9]+(?:[._]|__|-|/)?)*[a-z0-9]+)\"\n static let tagPattern = \"(?::(?[\\\\w][\\\\w.-]{0,127}))?(?:@(?sha256:[0-9a-fA-F]{64}))?\"\n static let pathTagPattern = \"\\(pathPattern)\\(tagPattern)\"\n\n public init(path: String, domain: String? = nil, tag: String? = nil, digest: String? = nil) throws {\n if let domain, !domain.isEmpty {\n self._domain = domain\n }\n\n self._path = path\n self._tag = tag\n self._digest = digest\n }\n\n public static func parse(_ s: String) throws -> Reference {\n if s.count > referenceTotalLengthMax {\n throw ContainerizationError(.invalidArgument, message: \"Reference length \\(s.count) greater than \\(referenceTotalLengthMax)\")\n }\n\n let identifierRegex = try Regex(Self.identifierPattern)\n guard try identifierRegex.wholeMatch(in: s) == nil else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot specify 64 byte hex string as reference\")\n }\n\n let (domain, remainder) = try Self.parseDomain(from: s)\n let constructedRawReference: String = remainder\n if let domain {\n let domainRegex = try Regex(domainPattern)\n guard try domainRegex.wholeMatch(in: domain) != nil else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid domain \\(domain) for reference \\(s)\")\n }\n }\n let fields = try constructedRawReference.matches(regex: pathTagPattern)\n guard let path = fields[\"path\"] else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot parse path for reference \\(s)\")\n }\n\n let ref = try Reference(path: path, domain: domain)\n if ref.name.count > nameTotalLengthMax {\n throw ContainerizationError(.invalidArgument, message: \"Repo length \\(ref.name.count) greater than \\(nameTotalLengthMax)\")\n }\n\n // Extract tag and digest\n let tag = fields[\"tag\"] ?? \"\"\n let digest = fields[\"digest\"] ?? \"\"\n\n if !digest.isEmpty {\n return try ref.withDigest(digest)\n } else if !tag.isEmpty {\n return try ref.withTag(tag)\n }\n return ref\n }\n\n private static func parseDomain(from s: String) throws -> (domain: String?, remainder: String) {\n var domain: String? = nil\n var path: String = s\n let charset = CharacterSet(charactersIn: \".:\")\n let splits = s.split(separator: \"/\", maxSplits: 1)\n guard splits.count == 2 else {\n if s.starts(with: \"localhost\") {\n return (s, \"\")\n }\n return (nil, s)\n }\n let _domain = String(splits[0])\n let _path = String(splits[1])\n if _domain.starts(with: \"localhost\") || _domain.rangeOfCharacter(from: charset) != nil {\n domain = _domain\n path = _path\n }\n return (domain, path)\n }\n\n public static func withName(_ name: String) throws -> Reference {\n if name.count > nameTotalLengthMax {\n throw ContainerizationError(.invalidArgument, message: \"Name length \\(name.count) greater than \\(nameTotalLengthMax)\")\n }\n let fields = try name.matches(regex: Self.domainPattern)\n // Extract domain and path\n let domain = fields[\"domain\"] ?? \"\"\n let path = fields[\"path\"] ?? \"\"\n\n if domain.isEmpty || path.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Image reference domain or path is empty\")\n }\n\n return try Reference(path: path, domain: domain)\n }\n\n public func withTag(_ tag: String) throws -> Reference {\n var tag = tag\n if !tag.starts(with: \":\") {\n tag = \":\" + tag\n }\n let fields = try tag.matches(regex: Self.tagPattern)\n tag = fields[\"tag\"] ?? \"\"\n\n if tag.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Invalid format for image reference. Missing tag\")\n }\n return try Reference(path: self.path, domain: self.domain, tag: tag)\n }\n\n public func withDigest(_ digest: String) throws -> Reference {\n var digest = digest\n if !digest.starts(with: \"@\") {\n digest = \"@\" + digest\n }\n let fields = try digest.matches(regex: Self.tagPattern)\n digest = fields[\"digest\"] ?? \"\"\n\n if digest.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Invalid format for image reference. Missing digest\")\n }\n return try Reference(path: self.path, domain: self.domain, digest: digest)\n }\n\n private static func splitDomain(_ name: String) -> (domain: String, path: String) {\n let parts = name.split(separator: \"/\")\n guard parts.count == 2 else {\n return (\"\", name)\n }\n return (String(parts[0]), String(parts[1]))\n }\n\n /// Normalize the reference object.\n /// Normalization is useful in cases where the reference object is to be used to\n /// fetch/push an image from/to a remote registry.\n /// It does the following:\n /// - Adds a default tag of \"latest\" if the reference had no tag/digest set.\n /// - If the domain is \"registry-1.docker.io\" or \"docker.io\" and the path has no repository set,\n /// it adds a default \"library/\" repository name.\n public func normalize() {\n if let domain = self.domain, domain == dockerRegistryHost || domain == legacyDockerRegistryHost {\n // Check if the image is being referenced by a named tag.\n // If it is, and a repository is not specified, prefix it with \"library/\".\n // This needs to be done only if we are using the Docker registry.\n if !self.path.contains(\"/\") {\n self._path = \"\\(defaultDockerRegistryRepo)/\\(self._path)\"\n }\n }\n let identifier = self._tag ?? self._digest\n if identifier == nil {\n // If the user did not specify a tag or a digest for the reference, set the tag to \"latest\".\n self._tag = defaultTag\n }\n }\n\n public static func resolveDomain(domain: String) -> String {\n if domain == legacyDockerRegistryHost {\n return dockerRegistryHost\n }\n return domain\n }\n}\n\nextension String {\n func matches(regex: String) throws -> [String: String] {\n do {\n let regex = try NSRegularExpression(pattern: regex, options: [])\n let nsRange = NSRange(self.startIndex.. [String] {\n let pattern = self.pattern\n let regex = try NSRegularExpression(pattern: \"\\\\(\\\\?<(\\\\w+)>\", options: [])\n let nsRange = NSRange(pattern.startIndex.. StreamLogHandler {\n standardErrorLock.withLock {\n StreamLogHandler.standardError(label: label)\n }\n }\n\n static func main() async throws {\n LoggingSystem.bootstrap(standardError)\n var log = Logger(label: \"vminitd\")\n\n try adjustLimits()\n\n // when running under debug mode, launch vminitd as a sub process of pid1\n // so that we get a chance to collect better logs and errors before pid1 exists\n // and the kernel panics.\n #if DEBUG\n let environment = ProcessInfo.processInfo.environment\n let foreground = environment[Self.foregroundEnvVar]\n log.info(\"checking for shim var \\(foregroundEnvVar)=\\(String(describing: foreground))\")\n\n if foreground == nil {\n try runInForeground(log)\n exit(0)\n }\n\n // since we are not running as pid1 in this mode we must set ourselves\n // as a subpreaper so that all child processes are reaped by us and not\n // passed onto our parent.\n CZ_set_sub_reaper()\n #endif\n\n signal(SIGPIPE, SIG_IGN)\n\n // Because the sysctl rpc wouldn't make sense if this didn't always exist, we\n // ALWAYS mount /proc.\n guard Musl.mount(\"proc\", \"/proc\", \"proc\", 0, \"\") == 0 else {\n log.error(\"failed to mount /proc\")\n exit(1)\n }\n\n try Binfmt.mount()\n\n log.logLevel = .debug\n\n log.info(\"vminitd booting...\")\n let eg = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)\n let server = Initd(log: log, group: eg)\n\n do {\n log.info(\"serve vminitd api\")\n try await server.serve(port: vsockPort)\n log.info(\"vminitd api returned...\")\n } catch {\n log.error(\"vminitd boot error \\(error)\")\n exit(1)\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Spec.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// NOTE: This is not a complete recreation of the runtime spec. Other platforms outside of Linux\n/// have been left off, and some APIs for Linux aren't present. This was manually ported starting\n/// at the v1.2.0 release.\n\npublic struct Spec: Codable, Sendable {\n public var version: String\n public var hooks: Hook?\n public var process: Process?\n public var hostname, domainname: String\n public var mounts: [Mount]\n public var annotations: [String: String]?\n public var root: Root?\n public var linux: Linux?\n\n public init(\n version: String = \"\",\n hooks: Hook? = nil,\n process: Process? = nil,\n hostname: String = \"\",\n domainname: String = \"\",\n mounts: [Mount] = [],\n annotations: [String: String]? = nil,\n root: Root? = nil,\n linux: Linux? = nil\n ) {\n self.version = version\n self.hooks = hooks\n self.process = process\n self.hostname = hostname\n self.domainname = domainname\n self.mounts = mounts\n self.annotations = annotations\n self.root = root\n self.linux = linux\n }\n\n public enum CodingKeys: String, CodingKey {\n case version = \"ociVersion\"\n case hooks\n case process\n case hostname\n case domainname\n case mounts\n case annotations\n case root\n case linux\n }\n}\n\npublic struct Process: Codable, Sendable {\n public var cwd: String\n public var env: [String]\n public var consoleSize: Box?\n public var selinuxLabel: String\n public var noNewPrivileges: Bool\n public var commandLine: String\n public var oomScoreAdj: Int?\n public var capabilities: LinuxCapabilities?\n public var apparmorProfile: String\n public var user: User\n public var rlimits: [POSIXRlimit]\n public var args: [String]\n public var terminal: Bool\n\n public init(\n args: [String] = [],\n cwd: String = \"/\",\n env: [String] = [],\n consoleSize: Box? = nil,\n selinuxLabel: String = \"\",\n noNewPrivileges: Bool = false,\n commandLine: String = \"\",\n oomScoreAdj: Int? = nil,\n capabilities: LinuxCapabilities? = nil,\n apparmorProfile: String = \"\",\n user: User = .init(),\n rlimits: [POSIXRlimit] = [],\n terminal: Bool = false\n ) {\n self.cwd = cwd\n self.env = env\n self.consoleSize = consoleSize\n self.selinuxLabel = selinuxLabel\n self.noNewPrivileges = noNewPrivileges\n self.commandLine = commandLine\n self.oomScoreAdj = oomScoreAdj\n self.capabilities = capabilities\n self.apparmorProfile = apparmorProfile\n self.user = user\n self.rlimits = rlimits\n self.args = args\n self.terminal = terminal\n }\n\n public init(from config: ImageConfig) {\n let cwd = config.workingDir ?? \"/\"\n let env = config.env ?? []\n let args = (config.entrypoint ?? []) + (config.cmd ?? [])\n let user: User = {\n if let rawString = config.user {\n return User(username: rawString)\n }\n return User()\n }()\n self.init(args: args, cwd: cwd, env: env, user: user)\n }\n}\n\npublic struct LinuxCapabilities: Codable, Sendable {\n public var bounding: [String]\n public var effective: [String]\n public var inheritable: [String]\n public var permitted: [String]\n public var ambient: [String]\n\n public init(\n bounding: [String],\n effective: [String],\n inheritable: [String],\n permitted: [String],\n ambient: [String]\n ) {\n self.bounding = bounding\n self.effective = effective\n self.inheritable = inheritable\n self.permitted = permitted\n self.ambient = ambient\n }\n}\n\npublic struct Box: Codable, Sendable {\n var height, width: UInt\n\n public init(height: UInt, width: UInt) {\n self.height = height\n self.width = width\n }\n}\n\npublic struct User: Codable, Sendable {\n public var uid: UInt32\n public var gid: UInt32\n public var umask: UInt32?\n public var additionalGids: [UInt32]\n public var username: String\n\n public init(\n uid: UInt32 = 0,\n gid: UInt32 = 0,\n umask: UInt32? = nil,\n additionalGids: [UInt32] = [],\n username: String = \"\"\n ) {\n self.uid = uid\n self.gid = gid\n self.umask = umask\n self.additionalGids = additionalGids\n self.username = username\n }\n}\n\npublic struct Root: Codable, Sendable {\n public var path: String\n public var readonly: Bool\n\n public init(path: String, readonly: Bool) {\n self.path = path\n self.readonly = readonly\n }\n}\n\npublic struct Mount: Codable, Sendable {\n public var type: String\n public var source: String\n public var destination: String\n public var options: [String]\n\n public var uidMappings: [LinuxIDMapping]\n public var gidMappings: [LinuxIDMapping]\n\n public init(\n type: String,\n source: String,\n destination: String,\n options: [String] = [],\n uidMappings: [LinuxIDMapping] = [],\n gidMappings: [LinuxIDMapping] = []\n ) {\n self.destination = destination\n self.type = type\n self.source = source\n self.options = options\n self.uidMappings = uidMappings\n self.gidMappings = gidMappings\n }\n}\n\npublic struct Hook: Codable, Sendable {\n public var path: String\n public var args: [String]\n public var env: [String]\n public var timeout: Int?\n\n public init(path: String, args: [String], env: [String], timeout: Int?) {\n self.path = path\n self.args = args\n self.env = env\n self.timeout = timeout\n }\n}\n\npublic struct Hooks: Codable, Sendable {\n public var prestart: [Hook]\n public var createRuntime: [Hook]\n public var createContainer: [Hook]\n public var startContainer: [Hook]\n public var poststart: [Hook]\n public var poststop: [Hook]\n\n public init(\n prestart: [Hook],\n createRuntime: [Hook],\n createContainer: [Hook],\n startContainer: [Hook],\n poststart: [Hook],\n poststop: [Hook]\n ) {\n self.prestart = prestart\n self.createRuntime = createRuntime\n self.createContainer = createContainer\n self.startContainer = startContainer\n self.poststart = poststart\n self.poststop = poststop\n }\n}\n\npublic struct Linux: Codable, Sendable {\n public var uidMappings: [LinuxIDMapping]\n public var gidMappings: [LinuxIDMapping]\n public var sysctl: [String: String]?\n public var resources: LinuxResources?\n public var cgroupsPath: String\n public var namespaces: [LinuxNamespace]\n public var devices: [LinuxDevice]\n public var seccomp: LinuxSeccomp?\n public var rootfsPropagation: String\n public var maskedPaths: [String]\n public var readonlyPaths: [String]\n public var mountLabel: String\n public var personality: LinuxPersonality?\n\n public init(\n uidMappings: [LinuxIDMapping] = [],\n gidMappings: [LinuxIDMapping] = [],\n sysctl: [String: String]? = nil,\n resources: LinuxResources? = nil,\n cgroupsPath: String = \"\",\n namespaces: [LinuxNamespace] = [],\n devices: [LinuxDevice] = [],\n seccomp: LinuxSeccomp? = nil,\n rootfsPropagation: String = \"\",\n maskedPaths: [String] = [],\n readonlyPaths: [String] = [],\n mountLabel: String = \"\",\n personality: LinuxPersonality? = nil\n ) {\n self.uidMappings = uidMappings\n self.gidMappings = gidMappings\n self.sysctl = sysctl\n self.resources = resources\n self.cgroupsPath = cgroupsPath\n self.namespaces = namespaces\n self.devices = devices\n self.seccomp = seccomp\n self.rootfsPropagation = rootfsPropagation\n self.maskedPaths = maskedPaths\n self.readonlyPaths = readonlyPaths\n self.mountLabel = mountLabel\n self.personality = personality\n }\n}\n\npublic struct LinuxNamespace: Codable, Sendable {\n public var type: LinuxNamespaceType\n public var path: String\n\n public init(type: LinuxNamespaceType, path: String = \"\") {\n self.type = type\n self.path = path\n }\n}\n\npublic enum LinuxNamespaceType: String, Codable, Sendable {\n case pid\n case network\n case uts\n case mount\n case ipc\n case user\n case cgroup\n}\n\npublic struct LinuxIDMapping: Codable, Sendable {\n public var containerID: UInt32\n public var hostID: UInt32\n public var size: UInt32\n\n public init(containerID: UInt32, hostID: UInt32, size: UInt32) {\n self.containerID = containerID\n self.hostID = hostID\n self.size = size\n }\n}\n\npublic struct POSIXRlimit: Codable, Sendable {\n public var type: String\n public var hard: UInt64\n public var soft: UInt64\n\n public init(type: String, hard: UInt64, soft: UInt64) {\n self.type = type\n self.hard = hard\n self.soft = soft\n }\n}\n\npublic struct LinuxHugepageLimit: Codable, Sendable {\n public var pagesize: String\n public var limit: UInt64\n\n public init(pagesize: String, limit: UInt64) {\n self.pagesize = pagesize\n self.limit = limit\n }\n}\n\npublic struct LinuxInterfacePriority: Codable, Sendable {\n public var name: String\n public var priority: UInt32\n\n public init(name: String, priority: UInt32) {\n self.name = name\n self.priority = priority\n }\n}\n\npublic struct LinuxBlockIODevice: Codable, Sendable {\n public var major: Int64\n public var minor: Int64\n\n public init(major: Int64, minor: Int64) {\n self.major = major\n self.minor = minor\n }\n}\n\npublic struct LinuxWeightDevice: Codable, Sendable {\n public var major: Int64\n public var minor: Int64\n public var weight: UInt16?\n public var leafWeight: UInt16?\n\n public init(major: Int64, minor: Int64, weight: UInt16?, leafWeight: UInt16?) {\n self.major = major\n self.minor = minor\n self.weight = weight\n self.leafWeight = leafWeight\n }\n}\n\npublic struct LinuxThrottleDevice: Codable, Sendable {\n public var major: Int64\n public var minor: Int64\n public var rate: UInt64\n\n public init(major: Int64, minor: Int64, rate: UInt64) {\n self.major = major\n self.minor = minor\n self.rate = rate\n }\n}\n\npublic struct LinuxBlockIO: Codable, Sendable {\n public var weight: UInt16?\n public var leafWeight: UInt16?\n public var weightDevice: [LinuxWeightDevice]\n public var throttleReadBpsDevice: [LinuxThrottleDevice]\n public var throttleWriteBpsDevice: [LinuxThrottleDevice]\n public var throttleReadIOPSDevice: [LinuxThrottleDevice]\n public var throttleWriteIOPSDevice: [LinuxThrottleDevice]\n\n public init(\n weight: UInt16?,\n leafWeight: UInt16?,\n weightDevice: [LinuxWeightDevice],\n throttleReadBpsDevice: [LinuxThrottleDevice],\n throttleWriteBpsDevice: [LinuxThrottleDevice],\n throttleReadIOPSDevice: [LinuxThrottleDevice],\n throttleWriteIOPSDevice: [LinuxThrottleDevice]\n ) {\n self.weight = weight\n self.leafWeight = leafWeight\n self.weightDevice = weightDevice\n self.throttleReadBpsDevice = throttleReadBpsDevice\n self.throttleWriteBpsDevice = throttleWriteBpsDevice\n self.throttleReadIOPSDevice = throttleReadIOPSDevice\n self.throttleWriteIOPSDevice = throttleWriteIOPSDevice\n }\n}\n\npublic struct LinuxMemory: Codable, Sendable {\n public var limit: Int64?\n public var reservation: Int64?\n public var swap: Int64?\n public var kernel: Int64?\n public var kernelTCP: Int64?\n public var swappiness: UInt64?\n public var disableOOMKiller: Bool?\n public var useHierarchy: Bool?\n public var checkBeforeUpdate: Bool?\n\n public init(\n limit: Int64? = nil,\n reservation: Int64? = nil,\n swap: Int64? = nil,\n kernel: Int64? = nil,\n kernelTCP: Int64? = nil,\n swappiness: UInt64? = nil,\n disableOOMKiller: Bool? = nil,\n useHierarchy: Bool? = nil,\n checkBeforeUpdate: Bool? = nil\n ) {\n self.limit = limit\n self.reservation = reservation\n self.swap = swap\n self.kernel = kernel\n self.kernelTCP = kernelTCP\n self.swappiness = swappiness\n self.disableOOMKiller = disableOOMKiller\n self.useHierarchy = useHierarchy\n self.checkBeforeUpdate = checkBeforeUpdate\n }\n}\n\npublic struct LinuxCPU: Codable, Sendable {\n public var shares: UInt64?\n public var quota: Int64?\n public var burst: UInt64?\n public var period: UInt64?\n public var realtimeRuntime: Int64?\n public var realtimePeriod: Int64?\n public var cpus: String\n public var mems: String\n public var idle: Int64?\n\n public init(\n shares: UInt64?,\n quota: Int64?,\n burst: UInt64?,\n period: UInt64?,\n realtimeRuntime: Int64?,\n realtimePeriod: Int64?,\n cpus: String,\n mems: String,\n idle: Int64?\n ) {\n self.shares = shares\n self.quota = quota\n self.burst = burst\n self.period = period\n self.realtimeRuntime = realtimeRuntime\n self.realtimePeriod = realtimePeriod\n self.cpus = cpus\n self.mems = mems\n self.idle = idle\n }\n}\n\npublic struct LinuxPids: Codable, Sendable {\n public var limit: Int64\n\n public init(limit: Int64) {\n self.limit = limit\n }\n}\n\npublic struct LinuxNetwork: Codable, Sendable {\n public var classID: UInt32?\n public var priorities: [LinuxInterfacePriority]\n\n public init(classID: UInt32?, priorities: [LinuxInterfacePriority]) {\n self.classID = classID\n self.priorities = priorities\n }\n}\n\npublic struct LinuxRdma: Codable, Sendable {\n public var hcsHandles: UInt32?\n public var hcaObjects: UInt32?\n\n public init(hcsHandles: UInt32?, hcaObjects: UInt32?) {\n self.hcsHandles = hcsHandles\n self.hcaObjects = hcaObjects\n }\n}\n\npublic struct LinuxResources: Codable, Sendable {\n public var devices: [LinuxDeviceCgroup]\n public var memory: LinuxMemory?\n public var cpu: LinuxCPU?\n public var pids: LinuxPids?\n public var blockIO: LinuxBlockIO?\n public var hugepageLimits: [LinuxHugepageLimit]\n public var network: LinuxNetwork?\n public var rdma: [String: LinuxRdma]?\n public var unified: [String: String]?\n\n public init(\n devices: [LinuxDeviceCgroup] = [],\n memory: LinuxMemory? = nil,\n cpu: LinuxCPU? = nil,\n pids: LinuxPids? = nil,\n blockIO: LinuxBlockIO? = nil,\n hugepageLimits: [LinuxHugepageLimit] = [],\n network: LinuxNetwork? = nil,\n rdma: [String: LinuxRdma]? = nil,\n unified: [String: String] = [:]\n ) {\n self.devices = devices\n self.memory = memory\n self.cpu = cpu\n self.pids = pids\n self.blockIO = blockIO\n self.hugepageLimits = hugepageLimits\n self.network = network\n self.rdma = rdma\n self.unified = unified\n }\n}\n\npublic struct LinuxDevice: Codable, Sendable {\n public var path: String\n public var type: String\n public var major: Int64\n public var minor: Int64\n public var fileMode: UInt32?\n public var uid: UInt32?\n public var gid: UInt32?\n\n public init(\n path: String,\n type: String,\n major: Int64,\n minor: Int64,\n fileMode: UInt32?,\n uid: UInt32?,\n gid: UInt32?\n ) {\n self.path = path\n self.type = type\n self.major = major\n self.minor = minor\n self.fileMode = fileMode\n self.uid = uid\n self.gid = gid\n }\n}\n\npublic struct LinuxDeviceCgroup: Codable, Sendable {\n public var allow: Bool\n public var type: String\n public var major: Int64?\n public var minor: Int64?\n public var access: String?\n\n public init(allow: Bool, type: String, major: Int64?, minor: Int64?, access: String?) {\n self.allow = allow\n self.type = type\n self.major = major\n self.minor = minor\n self.access = access\n }\n}\n\npublic enum LinuxPersonalityDomain: String, Codable, Sendable {\n case perLinux = \"LINUX\"\n case perLinux32 = \"LINUX32\"\n}\n\npublic struct LinuxPersonality: Codable, Sendable {\n public var domain: LinuxPersonalityDomain\n public var flags: [String]\n\n public init(domain: LinuxPersonalityDomain, flags: [String]) {\n self.domain = domain\n self.flags = flags\n }\n}\n\npublic struct LinuxSeccomp: Codable, Sendable {\n public var defaultAction: LinuxSeccompAction\n public var defaultErrnoRet: UInt?\n public var architectures: [Arch]\n public var flags: [LinuxSeccompFlag]\n public var listenerPath: String\n public var listenerMetadata: String\n public var syscalls: [LinuxSyscall]\n\n public init(\n defaultAction: LinuxSeccompAction,\n defaultErrnoRet: UInt?,\n architectures: [Arch],\n flags: [LinuxSeccompFlag],\n listenerPath: String,\n listenerMetadata: String,\n syscalls: [LinuxSyscall]\n ) {\n self.defaultAction = defaultAction\n self.defaultErrnoRet = defaultErrnoRet\n self.architectures = architectures\n self.flags = flags\n self.listenerPath = listenerPath\n self.listenerMetadata = listenerMetadata\n self.syscalls = syscalls\n }\n}\n\npublic enum LinuxSeccompFlag: String, Codable, Sendable {\n case flagLog = \"SECCOMP_FILTER_FLAG_LOG\"\n case flagSpecAllow = \"SECCOMP_FILTER_FLAG_SPEC_ALLOW\"\n case flagWaitKillableRecv = \"SECCOMP_FILTER_FLAG_WAIT_KILLABLE_RECV\"\n}\n\npublic enum Arch: String, Codable, Sendable {\n case archX86 = \"SCMP_ARCH_X86\"\n case archX86_64 = \"SCMP_ARCH_X86_64\"\n case archX32 = \"SCMP_ARCH_X32\"\n case archARM = \"SCMP_ARCH_ARM\"\n case archAARCH64 = \"SCMP_ARCH_AARCH64\"\n case archMIPS = \"SCMP_ARCH_MIPS\"\n case archMIPS64 = \"SCMP_ARCH_MIPS64\"\n case archMIPS64N32 = \"SCMP_ARCH_MIPS64N32\"\n case archMIPSEL = \"SCMP_ARCH_MIPSEL\"\n case archMIPSEL64 = \"SCMP_ARCH_MIPSEL64\"\n case archMIPSEL64N32 = \"SCMP_ARCH_MIPSEL64N32\"\n case archPPC = \"SCMP_ARCH_PPC\"\n case archPPC64 = \"SCMP_ARCH_PPC64\"\n case archPPC64LE = \"SCMP_ARCH_PPC64LE\"\n case archS390 = \"SCMP_ARCH_S390\"\n case archS390X = \"SCMP_ARCH_S390X\"\n case archPARISC = \"SCMP_ARCH_PARISC\"\n case archPARISC64 = \"SCMP_ARCH_PARISC64\"\n case archRISCV64 = \"SCMP_ARCH_RISCV64\"\n}\n\npublic enum LinuxSeccompAction: String, Codable, Sendable {\n case actKill = \"SCMP_ACT_KILL\"\n case actKillProcess = \"SCMP_ACT_KILL_PROCESS\"\n case actKillThread = \"SCMP_ACT_KILL_THREAD\"\n case actTrap = \"SCMP_ACT_TRAP\"\n case actErrno = \"SCMP_ACT_ERRNO\"\n case actTrace = \"SCMP_ACT_TRACE\"\n case actAllow = \"SCMP_ACT_ALLOW\"\n case actLog = \"SCMP_ACT_LOG\"\n case actNotify = \"SCMP_ACT_NOTIFY\"\n}\n\npublic enum LinuxSeccompOperator: String, Codable, Sendable {\n case opNotEqual = \"SCMP_CMP_NE\"\n case opLessThan = \"SCMP_CMP_LT\"\n case opLessEqual = \"SCMP_CMP_LE\"\n case opEqualTo = \"SCMP_CMP_EQ\"\n case opGreaterEqual = \"SCMP_CMP_GE\"\n case opGreaterThan = \"SCMP_CMP_GT\"\n case opMaskedEqual = \"SCMP_CMP_MASKED_EQ\"\n}\n\npublic struct LinuxSeccompArg: Codable, Sendable {\n public var index: UInt\n public var value: UInt64\n public var valueTwo: UInt64\n public var op: LinuxSeccompOperator\n\n public init(index: UInt, value: UInt64, valueTwo: UInt64, op: LinuxSeccompOperator) {\n self.index = index\n self.value = value\n self.valueTwo = valueTwo\n self.op = op\n }\n}\n\npublic struct LinuxSyscall: Codable, Sendable {\n public var names: [String]\n public var action: LinuxSeccompAction\n public var errnoRet: UInt?\n public var args: [LinuxSeccompArg]\n\n public init(\n names: [String],\n action: LinuxSeccompAction,\n errnoRet: UInt?,\n args: [LinuxSeccompArg]\n ) {\n self.names = names\n self.action = action\n self.errnoRet = errnoRet\n self.args = args\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Linux/Binfmt.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n#if canImport(Musl)\nimport Musl\nprivate let _mount = Musl.mount\n#elseif canImport(Glibc)\nimport Glibc\nprivate let _mount = Glibc.mount\n#endif\n\n/// `Binfmt` is a utility type that contains static helpers and types for\n/// mounting the Linux binfmt_misc filesystem, and creating new binfmt entries.\npublic struct Binfmt: Sendable {\n /// Default mount path for binfmt_misc.\n public static let path = \"/proc/sys/fs/binfmt_misc\"\n\n /// Entry models a binfmt_misc entry.\n /// https://docs.kernel.org/admin-guide/binfmt-misc.html\n public struct Entry {\n public var name: String\n public var type: String\n public var offset: String\n public var magic: String\n public var mask: String\n public var flags: String\n\n public init(\n name: String,\n type: String = \"M\",\n offset: String = \"\",\n magic: String,\n mask: String,\n flags: String = \"CF\"\n ) {\n self.name = name\n self.type = type\n self.offset = offset\n self.magic = magic\n self.mask = mask\n self.flags = flags\n }\n\n /// Returns a binfmt `Entry` for amd64 ELF binaries.\n public static func amd64() -> Self {\n Binfmt.Entry(\n name: \"x86_64\",\n magic: #\"\\x7fELF\\x02\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x3e\\x00\"#,\n mask: #\"\\xff\\xff\\xff\\xff\\xff\\xfe\\xfe\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff\"#\n )\n }\n\n #if os(Linux)\n /// Register the passed in `binaryPath` as the interpreter for a new binfmt_misc entry.\n public func register(binaryPath: String) throws {\n let registration = \":\\(self.name):\\(self.type):\\(self.offset):\\(self.magic):\\(self.mask):\\(binaryPath):\\(self.flags)\"\n\n try registration.write(\n to: URL(fileURLWithPath: Binfmt.path).appendingPathComponent(\"register\"),\n atomically: false,\n encoding: .ascii\n )\n }\n\n /// Deregister the binfmt_misc entry described by the current object.\n public func deregister() throws {\n let data = \"-1\"\n try data.write(\n to: URL(fileURLWithPath: Binfmt.path).appendingPathComponent(self.name),\n atomically: false,\n encoding: .ascii\n )\n }\n #endif // os(Linux)\n }\n\n #if os(Linux)\n /// Crude check to see if /proc/sys/fs/binfmt_misc/register exists.\n public static func mounted() -> Bool {\n FileManager.default.fileExists(atPath: \"\\(Self.path)/register\")\n }\n\n /// Mount the binfmt_misc filesystem.\n public static func mount() throws {\n guard _mount(\"binfmt_misc\", Self.path, \"binfmt_misc\", 0, \"\") == 0 else {\n throw POSIXError.fromErrno()\n }\n }\n #endif // os(Linux)\n}\n"], ["/containerization/Sources/Containerization/VZVirtualMachine+Helpers.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport Logging\nimport Virtualization\nimport ContainerizationError\n\nextension VZVirtualMachine {\n nonisolated func connect(queue: DispatchQueue, port: UInt32) async throws -> VZVirtioSocketConnection {\n try await withCheckedThrowingContinuation { cont in\n queue.sync {\n guard let vsock = self.socketDevices[0] as? VZVirtioSocketDevice else {\n let error = ContainerizationError(.invalidArgument, message: \"no vsock device\")\n cont.resume(throwing: error)\n return\n }\n vsock.connect(toPort: port) { result in\n switch result {\n case .success(let conn):\n // `conn` isn't used concurrently.\n nonisolated(unsafe) let conn = conn\n cont.resume(returning: conn)\n case .failure(let error):\n cont.resume(throwing: error)\n }\n }\n }\n }\n }\n\n func listen(queue: DispatchQueue, port: UInt32, listener: VZVirtioSocketListener) throws {\n try queue.sync {\n guard let vsock = self.socketDevices[0] as? VZVirtioSocketDevice else {\n throw ContainerizationError(.invalidArgument, message: \"no vsock device\")\n }\n vsock.setSocketListener(listener, forPort: port)\n }\n }\n\n func removeListener(queue: DispatchQueue, port: UInt32) throws {\n try queue.sync {\n guard let vsock = self.socketDevices[0] as? VZVirtioSocketDevice else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"no vsock device to remove\"\n )\n }\n vsock.removeSocketListener(forPort: port)\n }\n }\n\n func start(queue: DispatchQueue) async throws {\n try await withCheckedThrowingContinuation { (cont: CheckedContinuation) in\n queue.sync {\n self.start { result in\n if case .failure(let error) = result {\n cont.resume(throwing: error)\n return\n }\n cont.resume()\n }\n }\n }\n }\n\n func stop(queue: DispatchQueue) async throws {\n try await withCheckedThrowingContinuation { (cont: CheckedContinuation) in\n queue.sync {\n self.stop { error in\n if let error {\n cont.resume(throwing: error)\n return\n }\n cont.resume()\n }\n }\n }\n }\n}\n\nextension VZVirtualMachine {\n func waitForAgent(queue: DispatchQueue) async throws -> FileHandle {\n let agentConnectionRetryCount: Int = 150\n let agentConnectionSleepDuration: Duration = .milliseconds(20)\n\n for _ in 0...agentConnectionRetryCount {\n do {\n return try await self.connect(queue: queue, port: Vminitd.port).dupHandle()\n } catch {\n try await Task.sleep(for: agentConnectionSleepDuration)\n continue\n }\n }\n throw ContainerizationError(.invalidArgument, message: \"no connection to agent socket\")\n }\n}\n\nextension VZVirtioSocketConnection {\n func dupHandle() -> FileHandle {\n let fd = dup(self.fileDescriptor)\n self.close()\n return FileHandle(fileDescriptor: fd, closeOnDealloc: false)\n }\n}\n\n#endif\n"], ["/containerization/vminitd/Sources/vminitd/ProcessSupervisor.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nactor ProcessSupervisor {\n private let queue: DispatchQueue\n // `DispatchSourceSignal` is thread-safe.\n private nonisolated(unsafe) let source: DispatchSourceSignal\n private var processes = [ManagedProcess]()\n\n var log: Logger?\n\n func setLog(_ log: Logger?) {\n self.log = log\n }\n\n static let `default` = ProcessSupervisor()\n\n let poller: Epoll\n\n private init() {\n let queue = DispatchQueue(label: \"process-supervisor\")\n self.source = DispatchSource.makeSignalSource(signal: SIGCHLD, queue: queue)\n self.queue = queue\n self.poller = try! Epoll()\n let t = Thread {\n try! self.poller.run()\n }\n t.start()\n }\n\n func ready() {\n self.source.setEventHandler {\n do {\n self.log?.debug(\"received SIGCHLD, reaping processes\")\n try self.handleSignal()\n } catch {\n self.log?.error(\"reaping processes failed\", metadata: [\"error\": \"\\(error)\"])\n }\n }\n self.source.resume()\n }\n\n private func handleSignal() throws {\n dispatchPrecondition(condition: .onQueue(queue))\n\n self.log?.debug(\"starting to wait4 processes\")\n let exited = Reaper.reap()\n self.log?.debug(\"finished wait4 of \\(exited.count) processes\")\n\n self.log?.debug(\"checking for exit of managed process\", metadata: [\"exits\": \"\\(exited)\", \"processes\": \"\\(processes.count)\"])\n let exitedProcesses = self.processes.filter { proc in\n exited.contains { pid, _ in\n proc.pid == pid\n }\n }\n\n for proc in exitedProcesses {\n let pid = proc.pid\n if pid <= 0 {\n continue\n }\n\n if let status = exited[pid] {\n self.log?.debug(\n \"managed process exited\",\n metadata: [\n \"pid\": \"\\(pid)\",\n \"status\": \"\\(status)\",\n \"count\": \"\\(processes.count - 1)\",\n ])\n proc.setExit(status)\n self.processes.removeAll(where: { $0.pid == pid })\n }\n }\n }\n\n func start(process: ManagedProcess) throws -> Int32 {\n self.log?.debug(\"in supervisor lock to start process\")\n defer {\n self.log?.debug(\"out of supervisor lock to start process\")\n }\n\n do {\n self.processes.append(process)\n return try process.start()\n } catch {\n self.log?.error(\"process start failed \\(error)\", metadata: [\"process-id\": \"\\(process.id)\"])\n throw error\n }\n }\n\n deinit {\n self.log?.info(\"process supervisor deinit\")\n source.cancel()\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/ArchiveWriterConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CArchive\n\n/// Represents the configuration settings for an `ArchiveWriter`.\n///\n/// This struct allows specifying the archive format, compression filter,\n/// various format-specific options, and preferred locales for string encoding.\npublic struct ArchiveWriterConfiguration {\n /// The desired archive format\n public var format: Format\n /// The compression filter to apply to the archive\n public var filter: Filter\n /// An array of format-specific options to apply to the archive.\n /// This includes options like compression level and extended attribute format.\n public var options: [Options]\n /// An array of preferred locale identifiers for string encoding\n public var locales: [String]\n\n /// Initializes a new `ArchiveWriterConfiguration`.\n ///\n /// Sets up the configuration with the specified format, filter, options, and locales.\n public init(\n format: Format, filter: Filter, options: [Options] = [], locales: [String] = [\"en_US.UTF-8\", \"C.UTF-8\"]\n ) {\n self.format = format\n self.filter = filter\n self.options = options\n self.locales = locales\n }\n}\n\nextension ArchiveWriter {\n internal func setFormat(_ format: Format) throws {\n guard let underlying = self.underlying else { throw ArchiveError.noUnderlyingArchive }\n let r = archive_write_set_format(underlying, format.code)\n guard r == ARCHIVE_OK else { throw ArchiveError.unableToSetFormat(r, format) }\n }\n\n internal func addFilter(_ filter: Filter) throws {\n guard let underlying = self.underlying else { throw ArchiveError.noUnderlyingArchive }\n let r = archive_write_add_filter(underlying, filter.code)\n guard r == ARCHIVE_OK else { throw ArchiveError.unableToAddFilter(r, filter) }\n }\n\n internal func setOptions(_ options: [Options]) throws {\n try options.forEach {\n switch $0 {\n case .compressionLevel(let level):\n try wrap(\n archive_write_set_option(underlying, nil, \"compression-level\", \"\\(level)\"),\n ArchiveError.unableToSetOption, underlying: self.underlying)\n case .compression(.store):\n try wrap(\n archive_write_set_option(underlying, nil, \"compression\", \"store\"), ArchiveError.unableToSetOption,\n underlying: self.underlying)\n case .compression(.deflate):\n try wrap(\n archive_write_set_option(underlying, nil, \"compression\", \"deflate\"), ArchiveError.unableToSetOption,\n underlying: self.underlying)\n case .xattrformat(let value):\n let v = value.description\n try wrap(\n archive_write_set_option(underlying, nil, \"xattrheader\", v), ArchiveError.unableToSetOption,\n underlying: self.underlying)\n }\n }\n }\n}\n\npublic enum Options {\n case compressionLevel(UInt32)\n case compression(Compression)\n case xattrformat(XattrFormat)\n\n public enum Compression {\n case store\n case deflate\n }\n\n public enum XattrFormat: String, CustomStringConvertible {\n case schily\n case libarchive\n case all\n\n public var description: String {\n switch self {\n case .libarchive:\n return \"LIBARCHIVE\"\n case .schily:\n return \"SCHILY\"\n case .all:\n return \"ALL\"\n }\n }\n }\n}\n\n/// An enumeration of the supported archive formats.\npublic enum Format: String, Sendable {\n /// POSIX-standard `ustar` archives\n case ustar\n case gnutar\n /// POSIX `pax interchange format` archives\n case pax\n case paxRestricted\n /// POSIX octet-oriented cpio archives\n case cpio\n case cpioNewc\n /// Zip archive\n case zip\n /// two different variants of shar archives\n case shar\n case sharDump\n /// ISO9660 CD images\n case iso9660\n /// 7-Zip archives\n case sevenZip\n /// ar archives\n case arBSD\n case arGNU\n /// mtree file tree descriptions\n case mtree\n /// XAR archives\n case xar\n\n internal var code: CInt {\n switch self {\n case .ustar: return ARCHIVE_FORMAT_TAR_USTAR\n case .pax: return ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE\n case .paxRestricted: return ARCHIVE_FORMAT_TAR_PAX_RESTRICTED\n case .gnutar: return ARCHIVE_FORMAT_TAR_GNUTAR\n case .cpio: return ARCHIVE_FORMAT_CPIO_POSIX\n case .cpioNewc: return ARCHIVE_FORMAT_CPIO_AFIO_LARGE\n case .zip: return ARCHIVE_FORMAT_ZIP\n case .shar: return ARCHIVE_FORMAT_SHAR_BASE\n case .sharDump: return ARCHIVE_FORMAT_SHAR_DUMP\n case .iso9660: return ARCHIVE_FORMAT_ISO9660\n case .sevenZip: return ARCHIVE_FORMAT_7ZIP\n case .arBSD: return ARCHIVE_FORMAT_AR_BSD\n case .arGNU: return ARCHIVE_FORMAT_AR_GNU\n case .mtree: return ARCHIVE_FORMAT_MTREE\n case .xar: return ARCHIVE_FORMAT_XAR\n }\n }\n}\n\n/// An enumeration of the supported filters (compression / encoding standards) for an archive.\npublic enum Filter: String, Sendable {\n case none\n case gzip\n case bzip2\n case compress\n case lzma\n case xz\n case uu\n case rpm\n case lzip\n case lrzip\n case lzop\n case grzip\n case lz4\n\n internal var code: CInt {\n switch self {\n case .none: return ARCHIVE_FILTER_NONE\n case .gzip: return ARCHIVE_FILTER_GZIP\n case .bzip2: return ARCHIVE_FILTER_BZIP2\n case .compress: return ARCHIVE_FILTER_COMPRESS\n case .lzma: return ARCHIVE_FILTER_LZMA\n case .xz: return ARCHIVE_FILTER_XZ\n case .uu: return ARCHIVE_FILTER_UU\n case .rpm: return ARCHIVE_FILTER_RPM\n case .lzip: return ARCHIVE_FILTER_LZIP\n case .lrzip: return ARCHIVE_FILTER_LRZIP\n case .lzop: return ARCHIVE_FILTER_LZOP\n case .grzip: return ARCHIVE_FILTER_GRZIP\n case .lz4: return ARCHIVE_FILTER_LZ4\n }\n }\n}\n"], ["/containerization/Sources/Containerization/Image/Unpacker/EXT4Unpacker.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\n#if os(macOS)\nimport ContainerizationArchive\nimport ContainerizationEXT4\nimport SystemPackage\n#endif\n\npublic struct EXT4Unpacker: Unpacker {\n let blockSizeInBytes: UInt64\n\n public init(blockSizeInBytes: UInt64) {\n self.blockSizeInBytes = blockSizeInBytes\n }\n\n public func unpack(_ image: Image, for platform: Platform, at path: URL, progress: ProgressHandler? = nil) async throws -> Mount {\n #if !os(macOS)\n throw ContainerizationError(.unsupported, message: \"Cannot unpack an image on current platform\")\n #else\n let blockPath = try prepareUnpackPath(path: path)\n let manifest = try await image.manifest(for: platform)\n let filesystem = try EXT4.Formatter(FilePath(path), minDiskSize: blockSizeInBytes)\n defer { try? filesystem.close() }\n\n for layer in manifest.layers {\n try Task.checkCancellation()\n let content = try await image.getContent(digest: layer.digest)\n\n let compression: ContainerizationArchive.Filter\n switch layer.mediaType {\n case MediaTypes.imageLayer, MediaTypes.dockerImageLayer:\n compression = .none\n case MediaTypes.imageLayerGzip, MediaTypes.dockerImageLayerGzip:\n compression = .gzip\n default:\n throw ContainerizationError(.unsupported, message: \"Media type \\(layer.mediaType) not supported.\")\n }\n try filesystem.unpack(\n source: content.path,\n format: .paxRestricted,\n compression: compression,\n progress: progress\n )\n }\n\n return .block(\n format: \"ext4\",\n source: blockPath,\n destination: \"/\",\n options: []\n )\n #endif\n }\n\n private func prepareUnpackPath(path: URL) throws -> String {\n let blockPath = path.absolutePath()\n guard !FileManager.default.fileExists(atPath: blockPath) else {\n throw ContainerizationError(.exists, message: \"block device already exists at \\(blockPath)\")\n }\n return blockPath\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Linux/Epoll.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(Linux)\n\n#if canImport(Musl)\nimport Musl\n#elseif canImport(Glibc)\nimport Glibc\n#else\n#error(\"Epoll not supported on this platform\")\n#endif\n\nimport Foundation\nimport Synchronization\n\n/// Register file descriptors to receive events via Linux's\n/// epoll syscall surface.\npublic final class Epoll: Sendable {\n public typealias Mask = Int32\n public typealias Handler = (@Sendable (Mask) -> Void)\n\n private let epollFD: Int32\n private let handlers = SafeMap()\n private let pipe = Pipe() // to wake up a waiting epoll_wait\n\n public init() throws {\n let efd = epoll_create1(EPOLL_CLOEXEC)\n guard efd > 0 else {\n throw POSIXError.fromErrno()\n }\n self.epollFD = efd\n try self.add(pipe.fileHandleForReading.fileDescriptor) { _ in }\n }\n\n public func add(\n _ fd: Int32,\n mask: Int32 = EPOLLIN | EPOLLOUT, // HUP is always added\n handler: @escaping Handler\n ) throws {\n guard fcntl(fd, F_SETFL, O_NONBLOCK) == 0 else {\n throw POSIXError.fromErrno()\n }\n\n let events = EPOLLET | UInt32(bitPattern: mask)\n\n var event = epoll_event()\n event.events = events\n event.data.fd = fd\n\n try withUnsafeMutablePointer(to: &event) { ptr in\n while true {\n if epoll_ctl(self.epollFD, EPOLL_CTL_ADD, fd, ptr) == -1 {\n if errno == EAGAIN || errno == EINTR {\n continue\n }\n throw POSIXError.fromErrno()\n }\n break\n }\n }\n\n self.handlers.set(fd, handler)\n }\n\n /// Run the main epoll loop.\n ///\n /// max events to return in a single wait\n /// timeout in ms.\n /// -1 means block forever.\n /// 0 means return immediately if no events.\n public func run(maxEvents: Int = 128, timeout: Int32 = -1) throws {\n var events: [epoll_event] = .init(\n repeating: epoll_event(),\n count: maxEvents\n )\n\n while true {\n let n = epoll_wait(self.epollFD, &events, Int32(events.count), timeout)\n guard n >= 0 else {\n if errno == EINTR || errno == EAGAIN {\n continue // go back to epoll_wait\n }\n throw POSIXError.fromErrno()\n }\n\n if n == 0 {\n return // if epoll wait times out, then n will be 0\n }\n\n for i in 0.. Bool {\n errno == ENOENT || errno == EBADF || errno == EPERM\n }\n\n /// Shutdown the epoll handler.\n public func shutdown() throws {\n // wakes up epoll_wait and triggers a shutdown\n try self.pipe.fileHandleForWriting.close()\n }\n\n private final class SafeMap: Sendable {\n let dict = Mutex<[Key: Value]>([:])\n\n func set(_ key: Key, _ value: Value) {\n dict.withLock { @Sendable in\n $0[key] = value\n }\n }\n\n func get(_ key: Key) -> Value? {\n dict.withLock { @Sendable in\n $0[key]\n }\n }\n\n func del(_ key: Key) {\n dict.withLock { @Sendable in\n _ = $0.removeValue(forKey: key)\n }\n }\n }\n}\n\nextension Epoll.Mask {\n public var isHangup: Bool {\n (self & (EPOLLHUP | EPOLLERR | EPOLLRDHUP)) != 0\n }\n\n public var readyToRead: Bool {\n (self & EPOLLIN) != 0\n }\n\n public var readyToWrite: Bool {\n (self & EPOLLOUT) != 0\n }\n}\n\n#endif // os(Linux)\n"], ["/containerization/Sources/Containerization/NATNetworkInterface.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\n\nimport vmnet\nimport Virtualization\nimport ContainerizationError\nimport Foundation\nimport Synchronization\n\n/// An interface that uses NAT to provide an IP address for a given\n/// container/virtual machine.\n@available(macOS 26, *)\npublic final class NATNetworkInterface: Interface, Sendable {\n public var address: String {\n get {\n state.withLock { $0.address }\n }\n set {\n state.withLock { $0.address = newValue }\n }\n\n }\n\n public var gateway: String? {\n get {\n state.withLock { $0.gateway }\n }\n set {\n state.withLock { $0.gateway = newValue }\n }\n }\n\n @available(macOS 26, *)\n public var reference: vmnet_network_ref {\n state.withLock { $0.reference }\n }\n\n public var macAddress: String? {\n get {\n state.withLock { $0.macAddress }\n }\n set {\n state.withLock { $0.macAddress = newValue }\n }\n }\n\n private struct State {\n var address: String\n var gateway: String?\n var reference: vmnet_network_ref!\n var macAddress: String?\n }\n\n private let state: Mutex\n\n @available(macOS 26, *)\n public init(\n address: String,\n gateway: String?,\n reference: sending vmnet_network_ref,\n macAddress: String? = nil\n ) {\n let state = State(\n address: address,\n gateway: gateway,\n reference: reference,\n macAddress: macAddress\n )\n self.state = Mutex(state)\n }\n\n @available(macOS, obsoleted: 26, message: \"Use init(address:gateway:reference:macAddress:) instead\")\n public init(\n address: String,\n gateway: String?,\n macAddress: String? = nil\n ) {\n let state = State(\n address: address,\n gateway: gateway,\n reference: nil,\n macAddress: macAddress\n )\n self.state = Mutex(state)\n }\n}\n\n@available(macOS 26, *)\nextension NATNetworkInterface: VZInterface {\n public func device() throws -> VZVirtioNetworkDeviceConfiguration {\n let config = VZVirtioNetworkDeviceConfiguration()\n if let macAddress = self.macAddress {\n guard let mac = VZMACAddress(string: macAddress) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid mac address \\(macAddress)\")\n }\n config.macAddress = mac\n }\n\n config.attachment = VZVmnetNetworkDeviceAttachment(network: self.reference)\n return config\n }\n}\n\n#endif\n"], ["/containerization/Sources/Containerization/TimeSyncer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Logging\n\nactor TimeSyncer: Sendable {\n private var task: Task?\n private var context: Vminitd?\n private let logger: Logger?\n\n init(logger: Logger?) {\n self.logger = logger\n }\n\n func start(context: Vminitd, interval: Duration = .seconds(30)) {\n precondition(task == nil, \"time syncer is already running\")\n self.context = context\n self.task = Task {\n while true {\n do {\n do {\n try await Task.sleep(for: interval)\n } catch {\n return\n }\n\n var timeval = timeval()\n guard gettimeofday(&timeval, nil) == 0 else {\n throw POSIXError.fromErrno()\n }\n\n try await context.setTime(\n sec: Int64(timeval.tv_sec),\n usec: Int32(timeval.tv_usec)\n )\n } catch {\n self.logger?.error(\"failed to sync time with guest agent: \\(error)\")\n }\n }\n }\n }\n\n func close() async throws {\n guard let task else {\n preconditionFailure(\"time syncer was already closed\")\n }\n\n task.cancel()\n try await self.context?.close()\n self.task = nil\n self.context = nil\n }\n}\n"], ["/containerization/Sources/Containerization/HostsConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Static table lookups for a container. The values will be used to\n/// construct /etc/hosts for a given container.\npublic struct Hosts: Sendable {\n /// Represents one entry in an /etc/hosts file.\n public struct Entry: Sendable {\n /// The IPV4 or IPV6 address in String form.\n public var ipAddress: String\n /// The hostname(s) for the entry.\n public var hostnames: [String]\n /// An optional comment to be placed to the right side of the entry.\n public var comment: String?\n\n public init(ipAddress: String, hostnames: [String], comment: String? = nil) {\n self.comment = comment\n self.hostnames = hostnames\n self.ipAddress = ipAddress\n }\n\n /// The information in the structure rendered to a String representation\n /// that matches the format /etc/hosts expects.\n public var rendered: String {\n var line = ipAddress\n if !hostnames.isEmpty {\n line += \" \" + hostnames.joined(separator: \" \")\n }\n if let comment {\n line += \" # \\(comment) \"\n }\n return line\n }\n\n public static func localHostIPV4(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"127.0.0.1\",\n hostnames: [\"localhost\"],\n comment: comment\n )\n }\n\n public static func localHostIPV6(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"::1\",\n hostnames: [\"localhost\", \"ip6-localhost\", \"ip6-loopback\"],\n comment: comment\n )\n }\n\n public static func ipv6LocalNet(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"fe00::\",\n hostnames: [\"ip6-localnet\"],\n comment: comment\n )\n }\n\n public static func ipv6MulticastPrefix(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"ff00::\",\n hostnames: [\"ip6-mcastprefix\"],\n comment: comment\n )\n }\n\n public static func ipv6AllNodes(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"ff02::1\",\n hostnames: [\"ip6-allnodes\"],\n comment: comment\n )\n }\n\n public static func ipv6AllRouters(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"ff02::2\",\n hostnames: [\"ip6-allrouters\"],\n comment: comment\n )\n }\n }\n\n /// The entries to be written to /etc/hosts.\n public var entries: [Entry]\n\n /// A comment to render at the top of the file.\n public var comment: String?\n\n public init(\n entries: [Entry],\n comment: String? = nil\n ) {\n self.entries = entries\n self.comment = comment\n }\n}\n\nextension Hosts {\n /// A default entry that can be used for convenience. It contains a IPV4\n /// and IPV6 localhost entry, as well as ipv6 localnet, ipv6 mcastprefix,\n /// ipv6 allnodes, and ipv6 allrouters.\n public static let `default` = Hosts(entries: [\n Entry.localHostIPV4(),\n Entry.localHostIPV6(),\n Entry.ipv6LocalNet(),\n Entry.ipv6MulticastPrefix(),\n Entry.ipv6AllNodes(),\n Entry.ipv6AllRouters(),\n ])\n\n /// Returns a string variant of the data that can be written to\n /// /etc/hosts directly.\n public var hostsFile: String {\n var lines: [String] = []\n\n if let comment {\n lines.append(\"# \\(comment)\")\n }\n\n for entry in entries {\n lines.append(entry.rendered)\n }\n\n return lines.joined(separator: \"\\n\") + \"\\n\"\n }\n}\n"], ["/containerization/Sources/Containerization/Image/Image.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\n\n/// Type representing an OCI container image.\npublic struct Image: Sendable {\n private let contentStore: ContentStore\n /// The description for the image that comprises of its name and a reference to its root descriptor.\n public let description: Description\n\n /// A description of the OCI image.\n public struct Description: Sendable {\n /// The string reference of the image.\n public let reference: String\n /// The descriptor identifying the image.\n public let descriptor: Descriptor\n /// The digest for the image.\n public var digest: String { descriptor.digest }\n /// The media type of the image.\n public var mediaType: String { descriptor.mediaType }\n\n public init(reference: String, descriptor: Descriptor) {\n self.reference = reference\n self.descriptor = descriptor\n }\n }\n\n /// The descriptor for the image.\n public var descriptor: Descriptor { description.descriptor }\n /// The digest of the image.\n public var digest: String { description.digest }\n /// The media type of the image.\n public var mediaType: String { description.mediaType }\n /// The string reference for the image.\n public var reference: String { description.reference }\n\n public init(description: Description, contentStore: ContentStore) {\n self.description = description\n self.contentStore = contentStore\n }\n\n /// Returns the underlying OCI index for the image.\n public func index() async throws -> Index {\n guard let content: Content = try await contentStore.get(digest: digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(digest)\")\n }\n return try content.decode()\n }\n\n /// Returns the manifest for the specified platform.\n public func manifest(for platform: Platform) async throws -> Manifest {\n let index = try await self.index()\n let desc = index.manifests.first { desc in\n desc.platform == platform\n }\n guard let desc else {\n throw ContainerizationError(.unsupported, message: \"Platform \\(platform.description)\")\n }\n guard let content: Content = try await contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(digest)\")\n }\n return try content.decode()\n }\n\n /// Returns the descriptor for the given platform. If it does not exist\n /// will throw a ContainerizationError with the code set to .invalidArgument.\n public func descriptor(for platform: Platform) async throws -> Descriptor {\n let index = try await self.index()\n let desc = index.manifests.first { $0.platform == platform }\n guard let desc else {\n throw ContainerizationError(.invalidArgument, message: \"unsupported platform \\(platform)\")\n }\n return desc\n }\n\n /// Returns the OCI config for the specified platform.\n public func config(for platform: Platform) async throws -> ContainerizationOCI.Image {\n let manifest = try await self.manifest(for: platform)\n let desc = manifest.config\n guard let content: Content = try await contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(digest)\")\n }\n return try content.decode()\n }\n\n /// Returns a list of digests to all the referenced OCI objects.\n public func referencedDigests() async throws -> [String] {\n var referenced: [String] = [self.digest.trimmingDigestPrefix]\n let index = try await self.index()\n for manifest in index.manifests {\n referenced.append(manifest.digest.trimmingDigestPrefix)\n guard let m: Manifest = try? await contentStore.get(digest: manifest.digest) else {\n // If the requested digest does not exist or is not a manifest. Skip.\n // Its safe to skip processing this digest as it wont have any child layers.\n continue\n }\n let descs = m.layers + [m.config]\n referenced.append(contentsOf: descs.map { $0.digest.trimmingDigestPrefix })\n }\n return referenced\n }\n\n /// Returns a reference to the content blob for the image. The specified digest must be referenced by the image in one of its layers.\n public func getContent(digest: String) async throws -> Content {\n guard try await self.referencedDigests().contains(digest.trimmingDigestPrefix) else {\n throw ContainerizationError(.internalError, message: \"Image \\(self.reference) does not reference digest \\(digest)\")\n }\n guard let content: Content = try await contentStore.get(digest: digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(digest)\")\n }\n return content\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Socket/UnixType.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if canImport(Musl)\nimport Musl\nlet _SOCK_STREAM = SOCK_STREAM\n#elseif canImport(Glibc)\nimport Glibc\nlet _SOCK_STREAM = Int32(SOCK_STREAM.rawValue)\n#elseif canImport(Darwin)\nimport Darwin\nlet _SOCK_STREAM = SOCK_STREAM\n#else\n#error(\"UnixType not supported on this platform.\")\n#endif\n\n/// Unix domain socket variant of `SocketType`.\npublic struct UnixType: SocketType, Sendable, CustomStringConvertible {\n public var domain: Int32 { AF_UNIX }\n public var type: Int32 { _SOCK_STREAM }\n public var description: String {\n path\n }\n\n public let path: String\n public let perms: mode_t?\n private let _addr: sockaddr_un\n private let _unlinkExisting: Bool\n\n private init(sockaddr: sockaddr_un) {\n let pathname: String = withUnsafePointer(to: sockaddr.sun_path) { ptr in\n let charPtr = UnsafeRawPointer(ptr).assumingMemoryBound(to: CChar.self)\n return String(cString: charPtr)\n }\n self._addr = sockaddr\n self.path = pathname\n self._unlinkExisting = false\n self.perms = nil\n }\n\n /// Mode and unlinkExisting only used if the socket is going to be a listening socket.\n public init(\n path: String,\n perms: mode_t? = nil,\n unlinkExisting: Bool = false\n ) throws {\n self.path = path\n self.perms = perms\n self._unlinkExisting = unlinkExisting\n var addr = sockaddr_un()\n addr.sun_family = sa_family_t(AF_UNIX)\n\n let socketName = path\n let nameLength = socketName.utf8.count\n\n #if os(macOS)\n // Funnily enough, this isn't limited by sun path on macOS even though\n // it's stated as so.\n let lengthLimit = 253\n #elseif os(Linux)\n let lengthLimit = MemoryLayout.size(ofValue: addr.sun_path)\n #endif\n\n guard nameLength < lengthLimit else {\n throw Error.nameTooLong(path)\n }\n\n _ = withUnsafeMutablePointer(to: &addr.sun_path.0) { ptr in\n socketName.withCString { strncpy(ptr, $0, nameLength) }\n }\n\n #if os(macOS)\n addr.sun_len = UInt8(MemoryLayout.size + MemoryLayout.size + socketName.utf8.count + 1)\n #endif\n self._addr = addr\n }\n\n public func accept(fd: Int32) throws -> (Int32, SocketType) {\n var clientFD: Int32 = -1\n var addr = sockaddr_un()\n\n clientFD = Syscall.retrying {\n var size = socklen_t(MemoryLayout.stride)\n return withUnsafeMutablePointer(to: &addr) { pointer in\n pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { pointer in\n sysAccept(fd, pointer, &size)\n }\n }\n }\n if clientFD < 0 {\n throw Socket.errnoToError(msg: \"accept failed\")\n }\n\n return (clientFD, UnixType(sockaddr: addr))\n }\n\n public func beforeBind(fd: Int32) throws {\n #if os(Linux)\n // Only Linux supports setting the mode of a socket before binding.\n if let perms = self.perms {\n guard fchmod(fd, perms) == 0 else {\n throw Socket.errnoToError(msg: \"fchmod failed\")\n }\n }\n #endif\n\n var rc: Int32 = 0\n if self._unlinkExisting {\n rc = sysUnlink(self.path)\n if rc != 0 && errno != ENOENT {\n throw Socket.errnoToError(msg: \"failed to remove old socket at \\(self.path)\")\n }\n }\n }\n\n public func beforeListen(fd: Int32) throws {\n #if os(macOS)\n if let perms = self.perms {\n guard chmod(self.path, perms) == 0 else {\n throw Socket.errnoToError(msg: \"chmod failed\")\n }\n }\n #endif\n }\n\n public func withSockAddr(_ closure: (UnsafePointer, UInt32) throws -> Void) throws {\n var addr = self._addr\n try withUnsafePointer(to: &addr) {\n let addrBytes = UnsafeRawPointer($0).assumingMemoryBound(to: sockaddr.self)\n try closure(addrBytes, UInt32(MemoryLayout.stride))\n }\n }\n}\n\nextension UnixType {\n /// `UnixType` errors.\n public enum Error: Swift.Error, CustomStringConvertible {\n case nameTooLong(_: String)\n\n public var description: String {\n switch self {\n case .nameTooLong(let name):\n return \"\\(name) is too long for a Unix Domain Socket path\"\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Bundle.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\n\n#if canImport(Musl)\nimport Musl\nprivate let _mount = Musl.mount\nprivate let _umount = Musl.umount2\n#elseif canImport(Glibc)\nimport Glibc\nprivate let _mount = Glibc.mount\nprivate let _umount = Glibc.umount2\n#endif\n\n/// `Bundle` represents an OCI runtime spec bundle for running\n/// a container.\npublic struct Bundle: Sendable {\n /// The path to the bundle.\n public let path: URL\n\n /// The path to the OCI runtime spec config.json file.\n public var configPath: URL {\n self.path.appending(path: \"config.json\")\n }\n\n /// The path to a rootfs mount inside the bundle.\n public var rootfsPath: URL {\n self.path.appending(path: \"rootfs\")\n }\n\n /// Create the OCI bundle.\n ///\n /// - Parameters:\n /// - path: A URL pointing to where to create the bundle on the filesystem.\n /// - spec: A data blob that should contain an OCI runtime spec. This will be written\n /// to the bundle as a \"config.json\" file.\n public static func create(path: URL, spec: Data) throws -> Bundle {\n try self.init(path: path, spec: spec)\n }\n\n /// Create the OCI bundle.\n ///\n /// - Parameters:\n /// - path: A URL pointing to where to create the bundle on the filesystem.\n /// - spec: An OCI runtime spec that will be written to the bundle as a \"config.json\"\n /// file.\n public static func create(path: URL, spec: ContainerizationOCI.Spec) throws -> Bundle {\n try self.init(path: path, spec: spec)\n }\n\n /// Load an OCI bundle from the provided path.\n ///\n /// - Parameters:\n /// - path: A URL pointing to where to load the bundle from on the filesystem.\n public static func load(path: URL) throws -> Bundle {\n try self.init(path: path)\n }\n\n private init(path: URL) throws {\n let fm = FileManager.default\n if !fm.fileExists(atPath: path.path) {\n throw ContainerizationError(.invalidArgument, message: \"no bundle at \\(path.path)\")\n }\n self.path = path\n }\n\n // This constructor does not do any validation that data is actually a\n // valid OCI spec.\n private init(path: URL, spec: Data) throws {\n self.path = path\n\n let fm = FileManager.default\n try fm.createDirectory(\n atPath: self.path.appending(component: \"rootfs\").path,\n withIntermediateDirectories: true\n )\n\n try spec.write(to: self.configPath)\n }\n\n private init(path: URL, spec: ContainerizationOCI.Spec) throws {\n self.path = path\n\n let fm = FileManager.default\n try fm.createDirectory(\n atPath: self.path.appending(component: \"rootfs\").path,\n withIntermediateDirectories: true\n )\n\n let specData = try JSONEncoder().encode(spec)\n try specData.write(to: self.configPath)\n }\n\n /// Delete the OCI bundle from the filesystem.\n public func delete() throws {\n // Unmount, and then blow away the dir.\n #if os(Linux)\n let rootfs = self.rootfsPath.path\n guard _umount(rootfs, 0) == 0 else {\n throw POSIXError.fromErrno()\n }\n #endif\n // removeItem is recursive so should blow away the rootfs dir inside as well.\n let fm = FileManager.default\n try fm.removeItem(at: self.path)\n }\n\n /// Load and return the OCI runtime spec written to the bundle.\n public func loadConfig() throws -> ContainerizationOCI.Spec {\n let data = try Data(contentsOf: self.configPath)\n return try JSONDecoder().decode(ContainerizationOCI.Spec.self, from: data)\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/IOPair.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport Synchronization\n\nfinal class IOPair: Sendable {\n let readFrom: IOCloser\n let writeTo: IOCloser\n nonisolated(unsafe) let buffer: UnsafeMutableBufferPointer\n private let logger: Logger?\n\n private let done: Atomic\n\n init(readFrom: IOCloser, writeTo: IOCloser, logger: Logger? = nil) {\n self.readFrom = readFrom\n self.writeTo = writeTo\n self.done = Atomic(false)\n self.buffer = UnsafeMutableBufferPointer.allocate(capacity: Int(getpagesize()))\n self.logger = logger\n }\n\n func relay() throws {\n let readFromFd = self.readFrom.fileDescriptor\n let writeToFd = self.writeTo.fileDescriptor\n\n let readFrom = OSFile(fd: readFromFd)\n let writeTo = OSFile(fd: writeToFd)\n\n try ProcessSupervisor.default.poller.add(readFromFd, mask: EPOLLIN) { mask in\n if mask.isHangup && !mask.readyToRead {\n self.close()\n return\n }\n // Loop so that in the case that someone wrote > buf.count down the pipe\n // we properly will drain it fully.\n while true {\n let r = readFrom.read(self.buffer)\n if r.read > 0 {\n let view = UnsafeMutableBufferPointer(\n start: self.buffer.baseAddress,\n count: r.read\n )\n\n let w = writeTo.write(view)\n if w.wrote != r.read {\n self.logger?.error(\"stopping relay: short write for stdio\")\n self.close()\n return\n }\n }\n\n switch r.action {\n case .error(let errno):\n self.logger?.error(\"failed with errno \\(errno) while reading for fd \\(readFromFd)\")\n fallthrough\n case .eof:\n self.close()\n self.logger?.debug(\"closing relay for \\(readFromFd)\")\n return\n case .again:\n // We read all we could, exit.\n if mask.isHangup {\n self.close()\n }\n return\n default:\n break\n }\n }\n }\n }\n\n func close() {\n guard\n self.done.compareExchange(\n expected: false,\n desired: true,\n successOrdering: .acquiringAndReleasing,\n failureOrdering: .acquiring\n ).exchanged\n else {\n return\n }\n\n self.buffer.deallocate()\n\n let readFromFd = self.readFrom.fileDescriptor\n // Remove the fd from our global epoll instance first.\n do {\n try ProcessSupervisor.default.poller.delete(readFromFd)\n } catch {\n self.logger?.error(\"failed to delete fd from epoll \\(readFromFd): \\(error)\")\n }\n\n do {\n try self.readFrom.close()\n } catch {\n self.logger?.error(\"failed to close reader fd for IOPair: \\(error)\")\n }\n\n do {\n try self.writeTo.close()\n } catch {\n self.logger?.error(\"failed to close writer fd for IOPair: \\(error)\")\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Path.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// `Path` provides utilities to look for binaries in the current PATH,\n/// or to return the current PATH.\npublic struct Path {\n /// lookPath looks up an executable's path from $PATH\n public static func lookPath(_ name: String) -> URL? {\n lookup(name, path: getPath())\n }\n\n // getEnv returns the default environment of the process\n // with the default $PATH added for the context of a macOS application bundle\n public static func getEnv() -> [String: String] {\n var env = ProcessInfo.processInfo.environment\n env[\"PATH\"] = getPath()\n return env\n }\n\n private static func lookup(_ name: String, path: String) -> URL? {\n if name.contains(\"/\") {\n if findExec(name) {\n return URL(fileURLWithPath: name)\n }\n return nil\n }\n\n for var lookdir in path.split(separator: \":\") {\n if lookdir.isEmpty {\n lookdir = \".\"\n }\n let file = URL(fileURLWithPath: String(lookdir)).appendingPathComponent(name)\n if findExec(file.path) {\n return file\n }\n }\n return nil\n }\n\n /// getPath returns $PATH for the current process\n private static func getPath() -> String {\n let env = ProcessInfo.processInfo.environment\n return env[\"PATH\"] ?? \"/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin\"\n }\n\n // findPath returns a string containing the 'PATH' environment variable\n private static func findPath(_ env: [String]) -> String? {\n env.first(where: { path in\n let split = path.split(separator: \"=\")\n return split.count == 2 && split[0] == \"PATH\"\n })\n }\n\n // findExec returns true if the provided path is an executable\n private static func findExec(_ path: String) -> Bool {\n let fm = FileManager.default\n return fm.isExecutableFile(atPath: path)\n }\n}\n"], ["/containerization/Sources/ContainerizationIO/ReadStream.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport NIO\n\n/// `ReadStream` is a utility type for streaming data from a `URL`\n/// or `Data` blob.\npublic class ReadStream {\n public static let bufferSize = Int(1.mib())\n\n private var _stream: InputStream\n private let _buffSize: Int\n private let _data: Data?\n private let _url: URL?\n\n public init() {\n _stream = InputStream(data: .init())\n _buffSize = Self.bufferSize\n self._data = Data()\n self._url = nil\n }\n\n public init(url: URL, bufferSize: Int = bufferSize) throws {\n guard FileManager.default.fileExists(atPath: url.path) else {\n throw Error.noSuchFileOrDirectory(url)\n }\n guard let stream = InputStream(url: url) else {\n throw Error.failedToCreateStream\n }\n self._stream = stream\n self._buffSize = bufferSize\n self._url = url\n self._data = nil\n }\n\n public init(data: Data, bufferSize: Int = bufferSize) {\n self._stream = InputStream(data: data)\n self._buffSize = bufferSize\n self._url = nil\n self._data = data\n }\n\n /// Resets the read stream. This either reassigns\n /// the data buffer or url to a new InputStream internally.\n public func reset() throws {\n self._stream.close()\n if let url = self._url {\n guard let s = InputStream(url: url) else {\n throw Error.failedToCreateStream\n }\n self._stream = s\n return\n }\n let data = self._data ?? Data()\n self._stream = InputStream(data: data)\n }\n\n /// Get access to an `AsyncStream` of `ByteBuffer`'s from the input source.\n public var stream: AsyncStream {\n AsyncStream { cont in\n self._stream.open()\n defer { self._stream.close() }\n\n let readBuffer = UnsafeMutablePointer.allocate(capacity: _buffSize)\n\n while true {\n let byteRead = self._stream.read(readBuffer, maxLength: _buffSize)\n if byteRead <= 0 {\n readBuffer.deallocate()\n cont.finish()\n break\n } else {\n let data = Data(bytes: readBuffer, count: byteRead)\n let buffer = ByteBuffer(bytes: data)\n cont.yield(buffer)\n }\n }\n }\n }\n\n /// Get access to an `AsyncStream` of `Data` objects from the input source.\n public var dataStream: AsyncStream {\n AsyncStream { cont in\n self._stream.open()\n defer { self._stream.close() }\n\n let readBuffer = UnsafeMutablePointer.allocate(capacity: self._buffSize)\n while true {\n let byteRead = self._stream.read(readBuffer, maxLength: self._buffSize)\n if byteRead <= 0 {\n readBuffer.deallocate()\n cont.finish()\n break\n } else {\n let data = Data(bytes: readBuffer, count: byteRead)\n cont.yield(data)\n }\n }\n }\n }\n}\n\nextension ReadStream {\n /// Errors that can be encountered while using a `ReadStream`.\n public enum Error: Swift.Error, CustomStringConvertible {\n case failedToCreateStream\n case noSuchFileOrDirectory(_ p: URL)\n\n public var description: String {\n switch self {\n case .failedToCreateStream:\n return \"failed to create stream\"\n case .noSuchFileOrDirectory(let p):\n return \"no such file or directory: \\(p.path)\"\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+FileTree.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\nextension EXT4 {\n class FileTree {\n class FileTreeNode {\n let inode: InodeNumber\n let name: String\n var children: [Ptr] = []\n var blocks: (start: UInt32, end: UInt32)?\n var additionalBlocks: [(start: UInt32, end: UInt32)]?\n var link: InodeNumber?\n private var parent: Ptr?\n\n init(\n inode: InodeNumber,\n name: String,\n parent: Ptr?,\n children: [Ptr] = [],\n blocks: (start: UInt32, end: UInt32)? = nil,\n additionalBlocks: [(start: UInt32, end: UInt32)]? = nil,\n link: InodeNumber? = nil\n ) {\n self.inode = inode\n self.name = name\n self.children = children\n self.blocks = blocks\n self.additionalBlocks = additionalBlocks\n self.link = link\n self.parent = parent\n }\n\n deinit {\n self.children.removeAll()\n self.children = []\n self.blocks = nil\n self.additionalBlocks = nil\n self.link = nil\n }\n\n var path: FilePath? {\n var components: [String] = [self.name]\n var _ptr = self.parent\n while let ptr = _ptr {\n components.append(ptr.pointee.name)\n _ptr = ptr.pointee.parent\n }\n guard let last = components.last else {\n return nil\n }\n guard components.count > 1 else {\n return FilePath(last)\n }\n components = components.dropLast()\n let path = components.reversed().joined(separator: \"/\")\n guard let data = path.data(using: .utf8) else {\n return nil\n }\n guard let dataPath = String(data: data, encoding: .utf8) else {\n return nil\n }\n return FilePath(dataPath).pushing(FilePath(last)).lexicallyNormalized()\n }\n }\n\n var root: Ptr\n\n init(_ root: InodeNumber, _ name: String) {\n self.root = Ptr.allocate(capacity: 1)\n self.root.initialize(to: FileTreeNode(inode: root, name: name, parent: nil))\n }\n\n func lookup(path: FilePath) -> Ptr? {\n var components: [String] = path.items\n var node = self.root\n if components.first == \"/\" {\n components = Array(components.dropFirst())\n }\n if components.count == 0 {\n return node\n }\n for component in components {\n var found = false\n for childPtr in node.pointee.children {\n let child = childPtr.pointee\n if child.name == component {\n node = childPtr\n found = true\n break\n }\n }\n guard found else {\n return nil\n }\n }\n return node\n }\n }\n}\n"], ["/containerization/Sources/Containerization/Image/ImageStore/ImageStore+ReferenceManager.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\nextension ImageStore {\n /// A ReferenceManager handles the mappings between an image's\n /// reference and the underlying descriptor inside of a content store.\n internal actor ReferenceManager: Sendable {\n private let path: URL\n\n private typealias State = [String: Descriptor]\n private var images: State\n\n public init(path: URL) throws {\n try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true)\n\n self.path = path\n self.images = [:]\n }\n\n private func load() throws -> State {\n let statePath = self.path.appendingPathComponent(\"state.json\")\n guard FileManager.default.fileExists(atPath: statePath.absolutePath()) else {\n return [:]\n }\n do {\n let data = try Data(contentsOf: statePath)\n return try JSONDecoder().decode(State.self, from: data)\n } catch {\n throw ContainerizationError(.internalError, message: \"Failed to load image state \\(error.localizedDescription)\")\n }\n }\n\n private func save(_ state: State) throws {\n let statePath = self.path.appendingPathComponent(\"state.json\")\n try JSONEncoder().encode(state).write(to: statePath)\n }\n\n public func delete(reference: String) throws {\n var state = try self.load()\n state.removeValue(forKey: reference)\n try self.save(state)\n }\n\n public func delete(image: Image.Description) throws {\n try self.delete(reference: image.reference)\n }\n\n public func create(description: Image.Description) throws {\n var state = try self.load()\n state[description.reference] = description.descriptor\n try self.save(state)\n }\n\n public func list() throws -> [Image.Description] {\n let state = try self.load()\n return state.map { key, val in\n let description = Image.Description(reference: key, descriptor: val)\n return description\n }\n }\n\n public func get(reference: String) throws -> Image.Description {\n let images = try self.list()\n let hit = images.first(where: { image in\n image.reference == reference\n })\n guard let hit else {\n throw ContainerizationError(.notFound, message: \"image \\(reference) not found\")\n }\n return hit\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/ImageConfig.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// Source: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/config.go\n\nimport Foundation\n\n/// ImageConfig defines the execution parameters which should be used as a base when running a container using an image.\npublic struct ImageConfig: Codable, Sendable {\n enum CodingKeys: String, CodingKey {\n case user = \"User\"\n case env = \"Env\"\n case entrypoint = \"Entrypoint\"\n case cmd = \"Cmd\"\n case workingDir = \"WorkingDir\"\n case labels = \"Labels\"\n case stopSignal = \"StopSignal\"\n }\n\n /// user defines the username or UID which the process in the container should run as.\n public let user: String?\n\n /// env is a list of environment variables to be used in a container.\n public let env: [String]?\n\n /// entrypoint defines a list of arguments to use as the command to execute when the container starts.\n public let entrypoint: [String]?\n\n /// cmd defines the default arguments to the entrypoint of the container.\n public let cmd: [String]?\n\n /// workingDir sets the current working directory of the entrypoint process in the container.\n public let workingDir: String?\n\n /// labels contains arbitrary metadata for the container.\n public let labels: [String: String]?\n\n /// stopSignal contains the system call signal that will be sent to the container to exit.\n public let stopSignal: String?\n\n public init(\n user: String? = nil, env: [String]? = nil, entrypoint: [String]? = nil, cmd: [String]? = nil,\n workingDir: String? = nil, labels: [String: String]? = nil, stopSignal: String? = nil\n ) {\n self.user = user\n self.env = env\n self.entrypoint = entrypoint\n self.cmd = cmd\n self.workingDir = workingDir\n self.labels = labels\n self.stopSignal = stopSignal\n }\n}\n\n/// RootFS describes a layer content addresses\npublic struct Rootfs: Codable, Sendable {\n enum CodingKeys: String, CodingKey {\n case type\n case diffIDs = \"diff_ids\"\n }\n\n /// type is the type of the rootfs.\n public let type: String\n\n /// diffIDs is an array of layer content hashes (DiffIDs), in order from bottom-most to top-most.\n public let diffIDs: [String]\n\n public init(type: String, diffIDs: [String]) {\n self.type = type\n self.diffIDs = diffIDs\n }\n}\n\n/// History describes the history of a layer.\npublic struct History: Codable, Sendable {\n enum CodingKeys: String, CodingKey {\n case created\n case createdBy = \"created_by\"\n case author\n case comment\n case emptyLayer = \"empty_layer\"\n }\n\n /// created is the combined date and time at which the layer was created, formatted as defined by RFC 3339, section 5.6.\n public let created: String?\n\n /// createdBy is the command which created the layer.\n public let createdBy: String?\n\n /// author is the author of the build point.\n public let author: String?\n\n /// comment is a custom message set when creating the layer.\n public let comment: String?\n\n /// emptyLayer is used to mark if the history item created a filesystem diff.\n public let emptyLayer: Bool?\n\n public init(\n created: String? = nil, createdBy: String? = nil, author: String? = nil, comment: String? = nil,\n emptyLayer: Bool? = nil\n ) {\n self.created = created\n self.createdBy = createdBy\n self.author = author\n self.comment = comment\n self.emptyLayer = emptyLayer\n }\n}\n\n/// Image is the JSON structure which describes some basic information about the image.\n/// This provides the `application/vnd.oci.image.config.v1+json` mediatype when marshalled to JSON.\npublic struct Image: Codable, Sendable {\n /// created is the combined date and time at which the image was created, formatted as defined by RFC 3339, section 5.6.\n public let created: String?\n\n /// author defines the name and/or email address of the person or entity which created and is responsible for maintaining the image.\n public let author: String?\n\n /// architecture field specifies the CPU architecture, for example `amd64` or `ppc64`.\n public let architecture: String\n\n /// os specifies the operating system, for example `linux` or `windows`.\n public let os: String\n\n /// osVersion is an optional field specifying the operating system version, for example on Windows `10.0.14393.1066`.\n public let osVersion: String?\n\n /// osFeatures is an optional field specifying an array of strings, each listing a required OS feature (for example on Windows `win32k`).\n public let osFeatures: [String]?\n\n /// variant is an optional field specifying a variant of the CPU, for example `v7` to specify ARMv7 when architecture is `arm`.\n public let variant: String?\n\n /// config defines the execution parameters which should be used as a base when running a container using the image.\n public let config: ImageConfig?\n\n /// rootfs references the layer content addresses used by the image.\n public let rootfs: Rootfs\n\n /// history describes the history of each layer.\n public let history: [History]?\n\n public init(\n created: String? = nil, author: String? = nil, architecture: String, os: String, osVersion: String? = nil,\n osFeatures: [String]? = nil, variant: String? = nil, config: ImageConfig? = nil, rootfs: Rootfs,\n history: [History]? = nil\n ) {\n self.created = created\n self.author = author\n self.architecture = architecture\n self.os = os\n self.osVersion = osVersion\n self.osFeatures = osFeatures\n self.variant = variant\n self.config = config\n self.rootfs = rootfs\n self.history = history\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Terminal.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// `Terminal` provides a clean interface to deal with terminal interactions on Unix platforms.\npublic struct Terminal: Sendable {\n private let initState: termios?\n\n private var descriptor: Int32 {\n handle.fileDescriptor\n }\n public let handle: FileHandle\n\n public init(descriptor: Int32, setInitState: Bool = true) throws {\n if setInitState {\n self.initState = try Self.getattr(descriptor)\n } else {\n initState = nil\n }\n self.handle = .init(fileDescriptor: descriptor, closeOnDealloc: false)\n }\n\n /// Write the provided data to the tty device.\n public func write(_ data: Data) throws {\n try handle.write(contentsOf: data)\n }\n\n /// The winsize for a pty.\n public struct Size: Sendable {\n let size: winsize\n\n /// The width or `col` of the pty.\n public var width: UInt16 {\n size.ws_col\n }\n /// The height or `rows` of the pty.\n public var height: UInt16 {\n size.ws_row\n }\n\n init(_ size: winsize) {\n self.size = size\n }\n\n /// Set the size for use with a pty.\n public init(width cols: UInt16, height rows: UInt16) {\n self.size = winsize(ws_row: rows, ws_col: cols, ws_xpixel: 0, ws_ypixel: 0)\n }\n }\n\n /// Return the current pty attached to any of the STDIO descriptors.\n public static var current: Terminal {\n get throws {\n for i in [STDERR_FILENO, STDOUT_FILENO, STDIN_FILENO] {\n do {\n return try Terminal(descriptor: i)\n } catch {}\n }\n throw Error.notAPty\n }\n }\n\n /// The current window size for the pty.\n public var size: Size {\n get throws {\n var ws = winsize()\n try fromSyscall(ioctl(descriptor, UInt(TIOCGWINSZ), &ws))\n return Size(ws)\n }\n }\n\n /// Create a new pty pair.\n /// - Parameter initialSize: An initial size of the child pty.\n public static func create(initialSize: Size? = nil) throws -> (parent: Terminal, child: Terminal) {\n var parent: Int32 = 0\n var child: Int32 = 0\n let size = initialSize ?? Size(width: 120, height: 40)\n var ws = size.size\n\n try fromSyscall(openpty(&parent, &child, nil, nil, &ws))\n return (\n parent: try Terminal(descriptor: parent, setInitState: false),\n child: try Terminal(descriptor: child, setInitState: false)\n )\n }\n}\n\n// MARK: Errors\n\nextension Terminal {\n public enum Error: Swift.Error, CustomStringConvertible {\n case notAPty\n\n public var description: String {\n switch self {\n case .notAPty:\n return \"the provided fd is not a pty\"\n }\n }\n }\n}\n\nextension Terminal {\n /// Resize the current pty from the size of the provided pty.\n /// - Parameter pty: A pty to resize from.\n public func resize(from pty: Terminal) throws {\n var ws = try pty.size\n try fromSyscall(ioctl(descriptor, UInt(TIOCSWINSZ), &ws))\n }\n\n /// Resize the pty to the provided window size.\n /// - Parameter size: A window size for a pty.\n public func resize(size: Size) throws {\n var ws = size.size\n try fromSyscall(ioctl(descriptor, UInt(TIOCSWINSZ), &ws))\n }\n\n /// Resize the pty to the provided window size.\n /// - Parameter width: A width or cols of the terminal.\n /// - Parameter height: A height or rows of the terminal.\n public func resize(width: UInt16, height: UInt16) throws {\n var ws = Size(width: width, height: height)\n try fromSyscall(ioctl(descriptor, UInt(TIOCSWINSZ), &ws))\n }\n}\n\nextension Terminal {\n /// Enable raw mode for the pty.\n public func setraw() throws {\n var attr = try Self.getattr(descriptor)\n cfmakeraw(&attr)\n attr.c_oflag = attr.c_oflag | tcflag_t(OPOST)\n try fromSyscall(tcsetattr(descriptor, TCSANOW, &attr))\n }\n\n /// Enable echo support.\n /// Chars typed will be displayed to the terminal.\n public func enableEcho() throws {\n var attr = try Self.getattr(descriptor)\n attr.c_iflag &= ~tcflag_t(ICRNL)\n attr.c_lflag &= ~tcflag_t(ICANON | ECHO)\n try fromSyscall(tcsetattr(descriptor, TCSANOW, &attr))\n }\n\n /// Disable echo support.\n /// Chars typed will not be displayed back to the terminal.\n public func disableEcho() throws {\n var attr = try Self.getattr(descriptor)\n attr.c_lflag &= ~tcflag_t(ECHO)\n try fromSyscall(tcsetattr(descriptor, TCSANOW, &attr))\n }\n\n private static func getattr(_ fd: Int32) throws -> termios {\n var attr = termios()\n try fromSyscall(tcgetattr(fd, &attr))\n return attr\n }\n}\n\n// MARK: Reset\n\nextension Terminal {\n /// Close this pty's file descriptor.\n public func close() throws {\n do {\n // Use FileHandle's close directly as it sets the underlying fd in the object\n // to -1 for us.\n try self.handle.close()\n } catch {\n if let error = error as NSError?, error.domain == NSPOSIXErrorDomain {\n throw POSIXError(.init(rawValue: Int32(error.code))!)\n }\n throw error\n }\n }\n\n /// Reset the pty to its initial state.\n public func reset() throws {\n if var attr = initState {\n try fromSyscall(tcsetattr(descriptor, TCSANOW, &attr))\n }\n }\n\n /// Reset the pty to its initial state masking any errors.\n /// This is commonly used in a `defer` body to reset the current pty where the error code is not generally useful.\n public func tryReset() {\n try? reset()\n }\n}\n\nprivate func fromSyscall(_ status: Int32) throws {\n guard status == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/WriteEntry.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CArchive\nimport Foundation\n\n/// Represents a single entry (e.g., a file, directory, symbolic link)\n/// that is to be read/written into an archive.\npublic final class WriteEntry {\n let underlying: OpaquePointer\n\n public init(_ archive: ArchiveWriter) {\n underlying = archive_entry_new2(archive.underlying)\n }\n\n public init() {\n underlying = archive_entry_new()\n }\n\n deinit {\n archive_entry_free(underlying)\n }\n}\n\nextension WriteEntry {\n /// The size of the entry in bytes.\n public var size: Int64? {\n get {\n guard archive_entry_size_is_set(underlying) != 0 else { return nil }\n return archive_entry_size(underlying)\n }\n set {\n if let s = newValue {\n archive_entry_set_size(underlying, s)\n } else {\n archive_entry_unset_size(underlying)\n }\n }\n }\n\n /// The mode of the entry.\n public var permissions: mode_t {\n get {\n archive_entry_perm(underlying)\n }\n set {\n archive_entry_set_perm(underlying, newValue)\n }\n }\n\n /// The owner id of the entry.\n public var owner: uid_t? {\n get {\n uid_t(exactly: archive_entry_uid(underlying))\n }\n set {\n archive_entry_set_uid(underlying, Int64(newValue ?? 0))\n }\n }\n\n /// The group id of the entry\n public var group: gid_t? {\n get {\n gid_t(exactly: archive_entry_gid(underlying))\n }\n set {\n archive_entry_set_gid(underlying, Int64(newValue ?? 0))\n }\n }\n\n /// The path of file this entry hardlinks to\n public var hardlink: String? {\n get {\n guard let cstr = archive_entry_hardlink(underlying) else {\n return nil\n }\n return String(cString: cstr)\n }\n set {\n guard let newValue else {\n archive_entry_set_hardlink(underlying, nil)\n return\n }\n newValue.withCString {\n archive_entry_set_hardlink(underlying, $0)\n }\n }\n }\n\n /// The UTF-8 encoded path of file this entry hardlinks to\n public var hardlinkUtf8: String? {\n get {\n guard let cstr = archive_entry_hardlink_utf8(underlying) else {\n return nil\n }\n return String(cString: cstr, encoding: .utf8)\n }\n set {\n guard let newValue else {\n archive_entry_set_hardlink_utf8(underlying, nil)\n return\n }\n newValue.withCString {\n archive_entry_set_hardlink_utf8(underlying, $0)\n }\n }\n }\n\n /// The string representation of the permissions of the entry\n public var strmode: String? {\n if let cstr = archive_entry_strmode(underlying) {\n return String(cString: cstr)\n }\n return nil\n }\n\n /// The type of file this entry represents.\n public var fileType: URLFileResourceType {\n get {\n switch archive_entry_filetype(underlying) {\n case S_IFIFO: return .namedPipe\n case S_IFCHR: return .characterSpecial\n case S_IFDIR: return .directory\n case S_IFBLK: return .blockSpecial\n case S_IFREG: return .regular\n case S_IFLNK: return .symbolicLink\n case S_IFSOCK: return .socket\n default: return .unknown\n }\n }\n set {\n switch newValue {\n case .namedPipe: archive_entry_set_filetype(underlying, UInt32(S_IFIFO as mode_t))\n case .characterSpecial: archive_entry_set_filetype(underlying, UInt32(S_IFCHR as mode_t))\n case .directory: archive_entry_set_filetype(underlying, UInt32(S_IFDIR as mode_t))\n case .blockSpecial: archive_entry_set_filetype(underlying, UInt32(S_IFBLK as mode_t))\n case .regular: archive_entry_set_filetype(underlying, UInt32(S_IFREG as mode_t))\n case .symbolicLink: archive_entry_set_filetype(underlying, UInt32(S_IFLNK as mode_t))\n case .socket: archive_entry_set_filetype(underlying, UInt32(S_IFSOCK as mode_t))\n default: archive_entry_set_filetype(underlying, 0)\n }\n }\n }\n\n /// The date that the entry was last accessed\n public var contentAccessDate: Date? {\n get {\n Date(\n underlying,\n archive_entry_atime_is_set,\n archive_entry_atime,\n archive_entry_atime_nsec)\n }\n set {\n setDate(\n newValue,\n underlying, archive_entry_set_atime,\n archive_entry_unset_atime)\n }\n }\n\n /// The date that the entry was created\n public var creationDate: Date? {\n get {\n Date(\n underlying,\n archive_entry_ctime_is_set,\n archive_entry_ctime,\n archive_entry_ctime_nsec)\n }\n set {\n setDate(\n newValue,\n underlying, archive_entry_set_ctime,\n archive_entry_unset_ctime)\n }\n }\n\n /// The date that the entry was modified\n public var modificationDate: Date? {\n get {\n Date(\n underlying,\n archive_entry_mtime_is_set,\n archive_entry_mtime,\n archive_entry_mtime_nsec)\n }\n set {\n setDate(\n newValue,\n underlying, archive_entry_set_mtime,\n archive_entry_unset_mtime)\n }\n }\n\n /// The file path of the entry\n public var path: String? {\n get {\n guard let pathname = archive_entry_pathname(underlying) else {\n return nil\n }\n return String(cString: pathname)\n }\n set {\n guard let newValue else {\n archive_entry_set_pathname(underlying, nil)\n return\n }\n newValue.withCString {\n archive_entry_set_pathname(underlying, $0)\n }\n }\n }\n\n /// The UTF-8 encoded file path of the entry\n public var pathUtf8: String? {\n get {\n guard let pathname = archive_entry_pathname_utf8(underlying) else {\n return nil\n }\n return String(cString: pathname)\n }\n set {\n guard let newValue else {\n archive_entry_set_pathname_utf8(underlying, nil)\n return\n }\n newValue.withCString {\n archive_entry_set_pathname_utf8(underlying, $0)\n }\n }\n }\n\n /// The symlink target that the entry points to\n public var symlinkTarget: String? {\n get {\n guard let target = archive_entry_symlink(underlying) else {\n return nil\n }\n return String(cString: target)\n }\n set {\n guard let newValue else {\n archive_entry_set_symlink(underlying, nil)\n return\n }\n newValue.withCString {\n archive_entry_set_symlink(underlying, $0)\n }\n }\n }\n\n /// The extended attributes of the entry\n public var xattrs: [String: Data] {\n get {\n archive_entry_xattr_reset(self.underlying)\n var attrs: [String: Data] = [:]\n var namePtr: UnsafePointer?\n var valuePtr: UnsafeRawPointer?\n var size: Int = 0\n while archive_entry_xattr_next(self.underlying, &namePtr, &valuePtr, &size) == 0 {\n let _name = namePtr.map { String(cString: $0) }\n let _value = valuePtr.map { Data(bytes: $0, count: size) }\n guard let name = _name, let value = _value else {\n continue\n }\n attrs[name] = value\n }\n return attrs\n }\n set {\n archive_entry_xattr_clear(self.underlying)\n for (key, value) in newValue {\n value.withUnsafeBytes { ptr in\n archive_entry_xattr_add_entry(self.underlying, key, ptr.baseAddress, [UInt8](value).count)\n }\n }\n }\n }\n\n fileprivate func setDate(\n _ date: Date?, _ underlying: OpaquePointer, _ setter: (OpaquePointer, time_t, CLong) -> Void,\n _ unset: (OpaquePointer) -> Void\n ) {\n if let d = date {\n let ti = d.timeIntervalSince1970\n let seconds = floor(ti)\n let nsec = max(0, min(1_000_000_000, ti - seconds * 1_000_000_000))\n setter(underlying, time_t(seconds), CLong(nsec))\n } else {\n unset(underlying)\n }\n }\n}\n\nextension Date {\n init?(\n _ underlying: OpaquePointer, _ isSet: (OpaquePointer) -> CInt, _ seconds: (OpaquePointer) -> time_t,\n _ nsec: (OpaquePointer) -> CLong\n ) {\n guard isSet(underlying) != 0 else { return nil }\n let ti = TimeInterval(seconds(underlying)) + TimeInterval(nsec(underlying)) * 0.000_000_001\n self.init(timeIntervalSince1970: ti)\n }\n}\n"], ["/containerization/vminitd/Sources/vmexec/Mount.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Musl\n\nstruct ContainerMount {\n private let mounts: [ContainerizationOCI.Mount]\n private let rootfs: String\n\n init(rootfs: String, mounts: [ContainerizationOCI.Mount]) {\n self.rootfs = rootfs\n self.mounts = mounts\n }\n\n func mountToRootfs() throws {\n for m in self.mounts {\n let osMount = m.toOSMount()\n try osMount.mount(root: self.rootfs)\n }\n }\n\n func configureConsole() throws {\n let ptmx = self.rootfs.standardizingPath.appendingPathComponent(\"/dev/ptmx\")\n\n guard remove(ptmx) == 0 else {\n throw App.Errno(stage: \"remove(ptmx)\")\n }\n guard symlink(\"pts/ptmx\", ptmx) == 0 else {\n throw App.Errno(stage: \"symlink(pts/ptmx)\")\n }\n }\n\n private func mkdirAll(_ name: String, _ perm: Int16) throws {\n try FileManager.default.createDirectory(\n atPath: name,\n withIntermediateDirectories: true,\n attributes: [.posixPermissions: perm]\n )\n }\n}\n\nextension ContainerizationOCI.Mount {\n func toOSMount() -> ContainerizationOS.Mount {\n ContainerizationOS.Mount(\n type: self.type,\n source: self.source,\n target: self.destination,\n options: self.options\n )\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\n\n/**\n ```\n# EXT4 Filesystem Layout\n\n The EXT4 filesystem divides the disk into an upfront metadata section followed by several logical groups known as block groups. The\n metadata section looks like this:\n\n +--------------------------+\n | Boot Sector (1024) |\n +--------------------------+\n | Superblock (1024) |\n +--------------------------+\n | Empty (2048) |\n +--------------------------+\n | |\n | [Block Group Descriptors]|\n | |\n | - Free/used block bitmap |\n | - Free/used inode bitmap |\n | - Inode table pointer |\n | - Other metadata |\n | |\n +--------------------------+\n\n ## Block Groups\n\n Each block group optionally stores a copy of the superblock and group descriptor table for disaster recovery.\n The rest of the block group comprises of data blocks. The size of each block group is dynamically decided\n while formatting, based on total amount of space available on the disk.\n\n +--------------------------+\n | Block Group 0 |\n | +------------------+ |\n | | Super Block | |\n | +------------------+ |\n | | Group Desc. | |\n | +------------------+ |\n | | Data Blocks | |\n | | | |\n | +------------------+ |\n +--------------------------+\n | Block Group 1 |\n | +------------------+ |\n | | Super Block | |\n | +------------------+ |\n | | Group Desc. | |\n | +------------------+ |\n | | Data Blocks | |\n | | | |\n | +------------------+ |\n +--------------------------+\n | ... |\n +--------------------------+\n | Block Group N |\n | +------------------+ |\n | | Super Block | |\n | +------------------+ |\n | | Group Desc. | |\n | +------------------+ |\n | | Data Blocks | |\n | | | |\n | +------------------+ |\n +--------------------------+\n\n The descriptor for each block group contain the following information:\n\n - Block Bitmap\n - Inode Bitmap\n - Pointer to Inode Table\n - other metadata such as used block count, num. dirs etc.\n\n ### Block Bitmap\n\n A sequence of bits, where each bit represents a block in the block group.\n\n 1: In use block\n 0: Free block\n\n +---------------+---------------+\n | Block |\n | Bitmap |\n +---------------+---------------+\n | 1 0 1 0 1 1 0 0 |\n +---------------+---------------+\n | | | | | | | |\n | | | | | | | |\n v v v v v v v v\n +---+---+---+---+---+---+---+---+\n | B | | B | | B | B | | |\n +---+---+---+---+---+---+---+---+\n\n Whenever a file is created, free data blocks are identified by using this table.\n When it is deleted, the corresponding data blocks are marked as free.\n\n ### Inode Bitmap\n\n A sequence of bits, where each bit represents a inode in the block group. Since\n inodes per group is a fixed number, this bitmap is made to be of sufficient length\n to accommodate that many inodes\n\n 1: In use inode\n 0: Free inode\n\n +---------------+---------------+\n | Inode |\n | Bitmap |\n +---------------+---------------+\n | 1 0 1 0 1 1 0 0 |\n +---------------+---------------+\n | | | | | | | |\n | | | | | | | |\n v v v v v v v v\n +---+---+---+---+---+---+---+---+\n | I | | I | | I | I | | |\n +---+---+---+---+---+---+---+---+\n\n ## Inode table\n\n Inode table provides a mapping from Inode -> Data blocks. In this implementation, inode size is set to 256 bytes.\n Inode table uses extents to efficiently describe the mapping.\n\n +-----------------------+\n | Inode Table |\n +-----------------------+\n | Inode | Metadata |\n +-------+---------------+\n | 1 | permissions |\n | | size |\n | | user ID |\n | | group ID |\n | | timestamps |\n | | block |\n | | blocks count |\n +-------+---------------+\n | 2 | ... |\n +-------+---------------+\n | ... | ... |\n +-------+---------------+\n\n The length of `block` field in the inode table is 60 bytes. This field contains an extent tree\n that holds information about ranges of blocks used by the file. For smaller files, the entire extent\n tree can be stored within this field.\n\n +-----------------------+\n | Inode |\n +-----------------------+\n | Metadata |\n +-----------------------+\n | Extent Tree |\n | +-------------------+ |\n | | Extent Leaf Node | |\n | +-------------------+ |\n | | - Start Block | |\n | | - Block Count | |\n | | - ... | |\n | +-------------------+ |\n +-----------------------+\n\n For larger files which span across multiple non-contiguous blocks, extent tree's root points to extent\n blocks, which in-turn point to the blocks used by the file\n\n +-----------------------+\n | Extent Tree |\n | +-------------------+ |\n | | Extent Root | |\n | +-------------------+ |\n | | - Pointers to | |\n | | Extent Blocks | |\n | +-------------------+ |\n +-----------------------+\n |\n v\n +-----------------------+\n | Extent Block |\n +-----------------------+\n | +-------------------+ |\n | | Extent Leaf Node | |\n | +-------------------+ |\n | | - Start Block | |\n | | - Block Count | |\n | | - ... | |\n | +-------------------+ |\n | +-------------------+ |\n | | Extent Leaf Node | |\n | +-------------------+ |\n | | - Start Block | |\n | | - Block Count | |\n | | - ... | |\n | +-------------------+ |\n +-----------------------+\n\n ## Directory entries\n\n The data blocks for directory inodes point to a list of directory entrees. Each entry\n consists of only a name and inode number. The name and inode number correspond to the\n name and inode number of the children of the directory\n\n +-------------------------+\n | Directory Entry |\n +-------------------------+\n | inode | rec_len | name |\n +-------------------------+\n | 2 | 1 | \".\" |\n +-------------------------+\n | Directory Entry |\n +-------------------------+\n | inode | rec_len | name |\n +-------------------------+\n | 1 | 2 | \"..\" |\n +-------------------------+\n | Directory Entry |\n +-------------------------+\n | inode | rec_len | name |\n +-------------------------+\n | 11 | 10 | lost& |\n | | | found |\n +-------------------------+\n\nMore details can be found here https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout\n\n```\n*/\n\n/// A type for interacting with ext4 file systems.\n///\n/// The `Ext4` class provides functionality to read the superblock of an existing ext4 block device\n/// and format a new block device with the ext4 file system.\n///\n/// Usage:\n/// - To read the superblock of an existing ext4 block device, create an instance of `Ext4` with the\n/// path to the block device\n/// - To format a new block device with ext4, create an instance of `Ext4.Formatter` with the path to the block\n/// device and call the `close()` method.\n///\n/// Example 1: Read an existing block device\n/// ```swift\n/// let blockDevice = URL(filePath: \"/dev/sdb\")\n/// // succeeds if a valid ext4 fs is found at path\n/// let ext4 = try Ext4(blockDevice: blockDevice)\n/// print(\"Block size: \\(ext4.blockSize)\")\n/// print(\"Total size: \\(ext4.size)\")\n///\n/// // Reading the superblock\n/// let superblock = ext4.superblock\n/// print(\"Superblock information:\")\n/// print(\"Total blocks: \\(superblock.blocksCountLow)\")\n/// ```\n///\n/// Example 2: Format a new block device (Refer [`EXT4.Formatter`](x-source-tag://EXT4.Formatter) for more info)\n/// ```swift\n/// let devicePath = URL(filePath: \"/dev/sdc\")\n/// let formatter = try EXT4.Formatter(devicePath, blockSize: 4096)\n/// try formatter.close()\n/// ```\npublic enum EXT4 {\n public static let SuperBlockMagic: UInt16 = 0xef53\n\n static let ExtentHeaderMagic: UInt16 = 0xf30a\n static let XAttrHeaderMagic: UInt32 = 0xea02_0000\n\n static let DefectiveBlockInode: InodeNumber = 1\n static let RootInode: InodeNumber = 2\n static let FirstInode: InodeNumber = 11\n static let LostAndFoundInode: InodeNumber = 11\n\n static let InodeActualSize: UInt32 = 160 // 160 bytes used by metadata\n static let InodeExtraSize: UInt32 = 96 // 96 bytes for inline xattrs\n static let InodeSize: UInt32 = UInt32(MemoryLayout.size) // 256 bytes. This is the max size of an inode\n static let XattrInodeHeaderSize: UInt32 = 4\n static let XattrBlockHeaderSize: UInt32 = 32\n static let ExtraIsize: UInt16 = UInt16(InodeActualSize) - 128\n\n static let MaxLinks: UInt32 = 65000\n static let MaxBlocksPerExtent: UInt32 = 0x8000\n static let MaxFileSize: UInt64 = 128.gib()\n static let SuperBlockOffset: UInt64 = 1024\n}\n\nextension EXT4 {\n // `EXT4` errors.\n public enum Error: Swift.Error, CustomStringConvertible, Sendable, Equatable {\n case notFound(_ path: String)\n case couldNotReadSuperBlock(_ path: String, _ offset: UInt64, _ size: Int)\n case invalidSuperBlock\n case deepExtentsUnimplemented\n case invalidExtents\n case invalidXattrEntry\n case couldNotReadBlock(_ block: UInt32)\n case invalidPathEncoding(_ path: String)\n case couldNotReadInode(_ inode: UInt32)\n case couldNotReadGroup(_ group: UInt32)\n public var description: String {\n switch self {\n case .notFound(let path):\n return \"file at path \\(path) not found\"\n case .couldNotReadSuperBlock(let path, let offset, let size):\n return \"could not read \\(size) bytes of superblock from \\(path) at offset \\(offset)\"\n case .invalidSuperBlock:\n return \"not a valid EXT4 superblock\"\n case .deepExtentsUnimplemented:\n return \"deep extents are not supported\"\n case .invalidExtents:\n return \"extents invalid or corrupted\"\n case .invalidXattrEntry:\n return \"invalid extended attribute entry\"\n case .couldNotReadBlock(let block):\n return \"could not read block \\(block)\"\n case .invalidPathEncoding(let path):\n return \"path encoding for '\\(path)' is invalid, must be ascii or utf8\"\n case .couldNotReadInode(let inode):\n return \"could not read inode \\(inode)\"\n case .couldNotReadGroup(let group):\n return \"could not read group descriptor \\(group)\"\n }\n }\n }\n}\n"], ["/containerization/Sources/Containerization/SandboxContext/SandboxContext.grpc.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n// DO NOT EDIT.\n// swift-format-ignore-file\n//\n// Generated by the protocol buffer compiler.\n// Source: SandboxContext.proto\n//\nimport GRPC\nimport NIO\nimport NIOConcurrencyHelpers\nimport SwiftProtobuf\n\n\n/// Context for interacting with a container's runtime environment.\n///\n/// Usage: instantiate `Com_Apple_Containerization_Sandbox_V3_SandboxContextClient`, then call methods of this protocol to make API calls.\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextClientProtocol: GRPCClient {\n var serviceName: String { get }\n var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? { get }\n\n func mount(\n _ request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func umount(\n _ request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func setenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func getenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func mkdir(\n _ request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func sysctl(\n _ request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func setTime(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func setupEmulator(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func createProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func deleteProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func startProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func killProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func waitProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func resizeProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func closeProcessStdin(\n _ request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func proxyVsock(\n _ request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func stopVsockProxy(\n _ request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func ipLinkSet(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func ipAddrAdd(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func ipRouteAddLink(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func ipRouteAddDefault(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func configureDns(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func configureHosts(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func sync(\n _ request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func kill(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextClientProtocol {\n public var serviceName: String {\n return \"com.apple.containerization.sandbox.v3.SandboxContext\"\n }\n\n /// Mount a filesystem.\n ///\n /// - Parameters:\n /// - request: Request to send to Mount.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func mount(\n _ request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMountInterceptors() ?? []\n )\n }\n\n /// Unmount a filesystem.\n ///\n /// - Parameters:\n /// - request: Request to send to Umount.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func umount(\n _ request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.umount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeUmountInterceptors() ?? []\n )\n }\n\n /// Set an environment variable on the init process.\n ///\n /// - Parameters:\n /// - request: Request to send to Setenv.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func setenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetenvInterceptors() ?? []\n )\n }\n\n /// Get an environment variable from the init process.\n ///\n /// - Parameters:\n /// - request: Request to send to Getenv.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func getenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.getenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeGetenvInterceptors() ?? []\n )\n }\n\n /// Create a new directory inside the sandbox.\n ///\n /// - Parameters:\n /// - request: Request to send to Mkdir.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func mkdir(\n _ request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mkdir.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMkdirInterceptors() ?? []\n )\n }\n\n /// Set sysctls in the context of the sandbox.\n ///\n /// - Parameters:\n /// - request: Request to send to Sysctl.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func sysctl(\n _ request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sysctl.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSysctlInterceptors() ?? []\n )\n }\n\n /// Set time in the guest.\n ///\n /// - Parameters:\n /// - request: Request to send to SetTime.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func setTime(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setTime.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetTimeInterceptors() ?? []\n )\n }\n\n /// Set up an emulator in the guest for a specific binary format.\n ///\n /// - Parameters:\n /// - request: Request to send to SetupEmulator.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func setupEmulator(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setupEmulator.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetupEmulatorInterceptors() ?? []\n )\n }\n\n /// Create a new process inside the container.\n ///\n /// - Parameters:\n /// - request: Request to send to CreateProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func createProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.createProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateProcessInterceptors() ?? []\n )\n }\n\n /// Delete an existing process inside the container.\n ///\n /// - Parameters:\n /// - request: Request to send to DeleteProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func deleteProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.deleteProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeDeleteProcessInterceptors() ?? []\n )\n }\n\n /// Start the provided process.\n ///\n /// - Parameters:\n /// - request: Request to send to StartProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func startProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.startProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStartProcessInterceptors() ?? []\n )\n }\n\n /// Send a signal to the provided process.\n ///\n /// - Parameters:\n /// - request: Request to send to KillProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func killProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.killProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillProcessInterceptors() ?? []\n )\n }\n\n /// Wait for a process to exit and return the exit code.\n ///\n /// - Parameters:\n /// - request: Request to send to WaitProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func waitProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.waitProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeWaitProcessInterceptors() ?? []\n )\n }\n\n /// Resize the tty of a given process. This will error if the process does\n /// not have a pty allocated.\n ///\n /// - Parameters:\n /// - request: Request to send to ResizeProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func resizeProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.resizeProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeResizeProcessInterceptors() ?? []\n )\n }\n\n /// Close IO for a given process.\n ///\n /// - Parameters:\n /// - request: Request to send to CloseProcessStdin.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func closeProcessStdin(\n _ request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.closeProcessStdin.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCloseProcessStdinInterceptors() ?? []\n )\n }\n\n /// Proxy a vsock port to a unix domain socket in the guest, or vice versa.\n ///\n /// - Parameters:\n /// - request: Request to send to ProxyVsock.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func proxyVsock(\n _ request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.proxyVsock.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeProxyVsockInterceptors() ?? []\n )\n }\n\n /// Stop a vsock proxy to a unix domain socket.\n ///\n /// - Parameters:\n /// - request: Request to send to StopVsockProxy.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func stopVsockProxy(\n _ request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.stopVsockProxy.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStopVsockProxyInterceptors() ?? []\n )\n }\n\n /// Set the link state of a network interface.\n ///\n /// - Parameters:\n /// - request: Request to send to IpLinkSet.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func ipLinkSet(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipLinkSet.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpLinkSetInterceptors() ?? []\n )\n }\n\n /// Add an IPv4 address to a network interface.\n ///\n /// - Parameters:\n /// - request: Request to send to IpAddrAdd.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func ipAddrAdd(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipAddrAdd.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpAddrAddInterceptors() ?? []\n )\n }\n\n /// Add an IP route for a network interface.\n ///\n /// - Parameters:\n /// - request: Request to send to IpRouteAddLink.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func ipRouteAddLink(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddLink.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddLinkInterceptors() ?? []\n )\n }\n\n /// Add an IP route for a network interface.\n ///\n /// - Parameters:\n /// - request: Request to send to IpRouteAddDefault.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func ipRouteAddDefault(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddDefault.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddDefaultInterceptors() ?? []\n )\n }\n\n /// Configure DNS resolver.\n ///\n /// - Parameters:\n /// - request: Request to send to ConfigureDns.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func configureDns(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureDns.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureDnsInterceptors() ?? []\n )\n }\n\n /// Configure /etc/hosts.\n ///\n /// - Parameters:\n /// - request: Request to send to ConfigureHosts.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func configureHosts(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureHosts.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureHostsInterceptors() ?? []\n )\n }\n\n /// Perform the sync syscall.\n ///\n /// - Parameters:\n /// - request: Request to send to Sync.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func sync(\n _ request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sync.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSyncInterceptors() ?? []\n )\n }\n\n /// Send a signal to a process via the PID.\n ///\n /// - Parameters:\n /// - request: Request to send to Kill.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func kill(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.kill.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillInterceptors() ?? []\n )\n }\n}\n\n@available(*, deprecated)\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextClient: @unchecked Sendable {}\n\n@available(*, deprecated, renamed: \"Com_Apple_Containerization_Sandbox_V3_SandboxContextNIOClient\")\npublic final class Com_Apple_Containerization_Sandbox_V3_SandboxContextClient: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientProtocol {\n private let lock = Lock()\n private var _defaultCallOptions: CallOptions\n private var _interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol?\n public let channel: GRPCChannel\n public var defaultCallOptions: CallOptions {\n get { self.lock.withLock { return self._defaultCallOptions } }\n set { self.lock.withLockVoid { self._defaultCallOptions = newValue } }\n }\n public var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? {\n get { self.lock.withLock { return self._interceptors } }\n set { self.lock.withLockVoid { self._interceptors = newValue } }\n }\n\n /// Creates a client for the com.apple.containerization.sandbox.v3.SandboxContext service.\n ///\n /// - Parameters:\n /// - channel: `GRPCChannel` to the service host.\n /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them.\n /// - interceptors: A factory providing interceptors for each RPC.\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self._defaultCallOptions = defaultCallOptions\n self._interceptors = interceptors\n }\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SandboxContextNIOClient: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientProtocol {\n public var channel: GRPCChannel\n public var defaultCallOptions: CallOptions\n public var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol?\n\n /// Creates a client for the com.apple.containerization.sandbox.v3.SandboxContext service.\n ///\n /// - Parameters:\n /// - channel: `GRPCChannel` to the service host.\n /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them.\n /// - interceptors: A factory providing interceptors for each RPC.\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self.defaultCallOptions = defaultCallOptions\n self.interceptors = interceptors\n }\n}\n\n/// Context for interacting with a container's runtime environment.\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClientProtocol: GRPCClient {\n static var serviceDescriptor: GRPCServiceDescriptor { get }\n var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? { get }\n\n func makeMountCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeUmountCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeSetenvCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeGetenvCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeMkdirCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeSysctlCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeSetTimeCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeSetupEmulatorCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeCreateProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeDeleteProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeStartProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeKillProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeWaitProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeResizeProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeCloseProcessStdinCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeProxyVsockCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeStopVsockProxyCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeIpLinkSetCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeIpAddrAddCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeIpRouteAddLinkCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeIpRouteAddDefaultCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeConfigureDnsCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeConfigureHostsCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeSyncCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeKillCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClientProtocol {\n public static var serviceDescriptor: GRPCServiceDescriptor {\n return Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.serviceDescriptor\n }\n\n public var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? {\n return nil\n }\n\n public func makeMountCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMountInterceptors() ?? []\n )\n }\n\n public func makeUmountCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.umount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeUmountInterceptors() ?? []\n )\n }\n\n public func makeSetenvCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetenvInterceptors() ?? []\n )\n }\n\n public func makeGetenvCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.getenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeGetenvInterceptors() ?? []\n )\n }\n\n public func makeMkdirCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mkdir.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMkdirInterceptors() ?? []\n )\n }\n\n public func makeSysctlCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sysctl.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSysctlInterceptors() ?? []\n )\n }\n\n public func makeSetTimeCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setTime.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetTimeInterceptors() ?? []\n )\n }\n\n public func makeSetupEmulatorCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setupEmulator.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetupEmulatorInterceptors() ?? []\n )\n }\n\n public func makeCreateProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.createProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateProcessInterceptors() ?? []\n )\n }\n\n public func makeDeleteProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.deleteProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeDeleteProcessInterceptors() ?? []\n )\n }\n\n public func makeStartProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.startProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStartProcessInterceptors() ?? []\n )\n }\n\n public func makeKillProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.killProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillProcessInterceptors() ?? []\n )\n }\n\n public func makeWaitProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.waitProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeWaitProcessInterceptors() ?? []\n )\n }\n\n public func makeResizeProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.resizeProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeResizeProcessInterceptors() ?? []\n )\n }\n\n public func makeCloseProcessStdinCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.closeProcessStdin.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCloseProcessStdinInterceptors() ?? []\n )\n }\n\n public func makeProxyVsockCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.proxyVsock.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeProxyVsockInterceptors() ?? []\n )\n }\n\n public func makeStopVsockProxyCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.stopVsockProxy.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStopVsockProxyInterceptors() ?? []\n )\n }\n\n public func makeIpLinkSetCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipLinkSet.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpLinkSetInterceptors() ?? []\n )\n }\n\n public func makeIpAddrAddCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipAddrAdd.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpAddrAddInterceptors() ?? []\n )\n }\n\n public func makeIpRouteAddLinkCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddLink.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddLinkInterceptors() ?? []\n )\n }\n\n public func makeIpRouteAddDefaultCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddDefault.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddDefaultInterceptors() ?? []\n )\n }\n\n public func makeConfigureDnsCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureDns.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureDnsInterceptors() ?? []\n )\n }\n\n public func makeConfigureHostsCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureHosts.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureHostsInterceptors() ?? []\n )\n }\n\n public func makeSyncCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sync.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSyncInterceptors() ?? []\n )\n }\n\n public func makeKillCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.kill.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillInterceptors() ?? []\n )\n }\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClientProtocol {\n public func mount(\n _ request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_MountResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMountInterceptors() ?? []\n )\n }\n\n public func umount(\n _ request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_UmountResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.umount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeUmountInterceptors() ?? []\n )\n }\n\n public func setenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetenvResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetenvInterceptors() ?? []\n )\n }\n\n public func getenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_GetenvResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.getenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeGetenvInterceptors() ?? []\n )\n }\n\n public func mkdir(\n _ request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_MkdirResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mkdir.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMkdirInterceptors() ?? []\n )\n }\n\n public func sysctl(\n _ request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SysctlResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sysctl.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSysctlInterceptors() ?? []\n )\n }\n\n public func setTime(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetTimeResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setTime.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetTimeInterceptors() ?? []\n )\n }\n\n public func setupEmulator(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setupEmulator.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetupEmulatorInterceptors() ?? []\n )\n }\n\n public func createProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.createProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateProcessInterceptors() ?? []\n )\n }\n\n public func deleteProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.deleteProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeDeleteProcessInterceptors() ?? []\n )\n }\n\n public func startProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StartProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.startProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStartProcessInterceptors() ?? []\n )\n }\n\n public func killProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.killProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillProcessInterceptors() ?? []\n )\n }\n\n public func waitProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.waitProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeWaitProcessInterceptors() ?? []\n )\n }\n\n public func resizeProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.resizeProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeResizeProcessInterceptors() ?? []\n )\n }\n\n public func closeProcessStdin(\n _ request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.closeProcessStdin.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCloseProcessStdinInterceptors() ?? []\n )\n }\n\n public func proxyVsock(\n _ request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.proxyVsock.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeProxyVsockInterceptors() ?? []\n )\n }\n\n public func stopVsockProxy(\n _ request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.stopVsockProxy.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStopVsockProxyInterceptors() ?? []\n )\n }\n\n public func ipLinkSet(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipLinkSet.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpLinkSetInterceptors() ?? []\n )\n }\n\n public func ipAddrAdd(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipAddrAdd.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpAddrAddInterceptors() ?? []\n )\n }\n\n public func ipRouteAddLink(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddLink.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddLinkInterceptors() ?? []\n )\n }\n\n public func ipRouteAddDefault(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddDefault.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddDefaultInterceptors() ?? []\n )\n }\n\n public func configureDns(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureDns.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureDnsInterceptors() ?? []\n )\n }\n\n public func configureHosts(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureHosts.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureHostsInterceptors() ?? []\n )\n }\n\n public func sync(\n _ request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SyncResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sync.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSyncInterceptors() ?? []\n )\n }\n\n public func kill(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.kill.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillInterceptors() ?? []\n )\n }\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic struct Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClient: Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClientProtocol {\n public var channel: GRPCChannel\n public var defaultCallOptions: CallOptions\n public var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol?\n\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self.defaultCallOptions = defaultCallOptions\n self.interceptors = interceptors\n }\n}\n\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol: Sendable {\n\n /// - Returns: Interceptors to use when invoking 'mount'.\n func makeMountInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'umount'.\n func makeUmountInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'setenv'.\n func makeSetenvInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'getenv'.\n func makeGetenvInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'mkdir'.\n func makeMkdirInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'sysctl'.\n func makeSysctlInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'setTime'.\n func makeSetTimeInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'setupEmulator'.\n func makeSetupEmulatorInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'createProcess'.\n func makeCreateProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'deleteProcess'.\n func makeDeleteProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'startProcess'.\n func makeStartProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'killProcess'.\n func makeKillProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'waitProcess'.\n func makeWaitProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'resizeProcess'.\n func makeResizeProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'closeProcessStdin'.\n func makeCloseProcessStdinInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'proxyVsock'.\n func makeProxyVsockInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'stopVsockProxy'.\n func makeStopVsockProxyInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'ipLinkSet'.\n func makeIpLinkSetInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'ipAddrAdd'.\n func makeIpAddrAddInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'ipRouteAddLink'.\n func makeIpRouteAddLinkInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'ipRouteAddDefault'.\n func makeIpRouteAddDefaultInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'configureDns'.\n func makeConfigureDnsInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'configureHosts'.\n func makeConfigureHostsInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'sync'.\n func makeSyncInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'kill'.\n func makeKillInterceptors() -> [ClientInterceptor]\n}\n\npublic enum Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata {\n public static let serviceDescriptor = GRPCServiceDescriptor(\n name: \"SandboxContext\",\n fullName: \"com.apple.containerization.sandbox.v3.SandboxContext\",\n methods: [\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mount,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.umount,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setenv,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.getenv,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mkdir,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sysctl,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setTime,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setupEmulator,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.createProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.deleteProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.startProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.killProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.waitProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.resizeProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.closeProcessStdin,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.proxyVsock,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.stopVsockProxy,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipLinkSet,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipAddrAdd,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddLink,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddDefault,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureDns,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureHosts,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sync,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.kill,\n ]\n )\n\n public enum Methods {\n public static let mount = GRPCMethodDescriptor(\n name: \"Mount\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Mount\",\n type: GRPCCallType.unary\n )\n\n public static let umount = GRPCMethodDescriptor(\n name: \"Umount\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Umount\",\n type: GRPCCallType.unary\n )\n\n public static let setenv = GRPCMethodDescriptor(\n name: \"Setenv\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Setenv\",\n type: GRPCCallType.unary\n )\n\n public static let getenv = GRPCMethodDescriptor(\n name: \"Getenv\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Getenv\",\n type: GRPCCallType.unary\n )\n\n public static let mkdir = GRPCMethodDescriptor(\n name: \"Mkdir\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Mkdir\",\n type: GRPCCallType.unary\n )\n\n public static let sysctl = GRPCMethodDescriptor(\n name: \"Sysctl\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Sysctl\",\n type: GRPCCallType.unary\n )\n\n public static let setTime = GRPCMethodDescriptor(\n name: \"SetTime\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/SetTime\",\n type: GRPCCallType.unary\n )\n\n public static let setupEmulator = GRPCMethodDescriptor(\n name: \"SetupEmulator\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/SetupEmulator\",\n type: GRPCCallType.unary\n )\n\n public static let createProcess = GRPCMethodDescriptor(\n name: \"CreateProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/CreateProcess\",\n type: GRPCCallType.unary\n )\n\n public static let deleteProcess = GRPCMethodDescriptor(\n name: \"DeleteProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/DeleteProcess\",\n type: GRPCCallType.unary\n )\n\n public static let startProcess = GRPCMethodDescriptor(\n name: \"StartProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/StartProcess\",\n type: GRPCCallType.unary\n )\n\n public static let killProcess = GRPCMethodDescriptor(\n name: \"KillProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/KillProcess\",\n type: GRPCCallType.unary\n )\n\n public static let waitProcess = GRPCMethodDescriptor(\n name: \"WaitProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/WaitProcess\",\n type: GRPCCallType.unary\n )\n\n public static let resizeProcess = GRPCMethodDescriptor(\n name: \"ResizeProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ResizeProcess\",\n type: GRPCCallType.unary\n )\n\n public static let closeProcessStdin = GRPCMethodDescriptor(\n name: \"CloseProcessStdin\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/CloseProcessStdin\",\n type: GRPCCallType.unary\n )\n\n public static let proxyVsock = GRPCMethodDescriptor(\n name: \"ProxyVsock\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ProxyVsock\",\n type: GRPCCallType.unary\n )\n\n public static let stopVsockProxy = GRPCMethodDescriptor(\n name: \"StopVsockProxy\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/StopVsockProxy\",\n type: GRPCCallType.unary\n )\n\n public static let ipLinkSet = GRPCMethodDescriptor(\n name: \"IpLinkSet\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpLinkSet\",\n type: GRPCCallType.unary\n )\n\n public static let ipAddrAdd = GRPCMethodDescriptor(\n name: \"IpAddrAdd\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpAddrAdd\",\n type: GRPCCallType.unary\n )\n\n public static let ipRouteAddLink = GRPCMethodDescriptor(\n name: \"IpRouteAddLink\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpRouteAddLink\",\n type: GRPCCallType.unary\n )\n\n public static let ipRouteAddDefault = GRPCMethodDescriptor(\n name: \"IpRouteAddDefault\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpRouteAddDefault\",\n type: GRPCCallType.unary\n )\n\n public static let configureDns = GRPCMethodDescriptor(\n name: \"ConfigureDns\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ConfigureDns\",\n type: GRPCCallType.unary\n )\n\n public static let configureHosts = GRPCMethodDescriptor(\n name: \"ConfigureHosts\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ConfigureHosts\",\n type: GRPCCallType.unary\n )\n\n public static let sync = GRPCMethodDescriptor(\n name: \"Sync\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Sync\",\n type: GRPCCallType.unary\n )\n\n public static let kill = GRPCMethodDescriptor(\n name: \"Kill\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Kill\",\n type: GRPCCallType.unary\n )\n }\n}\n\n/// Context for interacting with a container's runtime environment.\n///\n/// To build a server, implement a class that conforms to this protocol.\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextProvider: CallHandlerProvider {\n var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextServerInterceptorFactoryProtocol? { get }\n\n /// Mount a filesystem.\n func mount(request: Com_Apple_Containerization_Sandbox_V3_MountRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Unmount a filesystem.\n func umount(request: Com_Apple_Containerization_Sandbox_V3_UmountRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Set an environment variable on the init process.\n func setenv(request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Get an environment variable from the init process.\n func getenv(request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Create a new directory inside the sandbox.\n func mkdir(request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Set sysctls in the context of the sandbox.\n func sysctl(request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Set time in the guest.\n func setTime(request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Set up an emulator in the guest for a specific binary format.\n func setupEmulator(request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Create a new process inside the container.\n func createProcess(request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Delete an existing process inside the container.\n func deleteProcess(request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Start the provided process.\n func startProcess(request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Send a signal to the provided process.\n func killProcess(request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Wait for a process to exit and return the exit code.\n func waitProcess(request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Resize the tty of a given process. This will error if the process does\n /// not have a pty allocated.\n func resizeProcess(request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Close IO for a given process.\n func closeProcessStdin(request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Proxy a vsock port to a unix domain socket in the guest, or vice versa.\n func proxyVsock(request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Stop a vsock proxy to a unix domain socket.\n func stopVsockProxy(request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Set the link state of a network interface.\n func ipLinkSet(request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Add an IPv4 address to a network interface.\n func ipAddrAdd(request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Add an IP route for a network interface.\n func ipRouteAddLink(request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Add an IP route for a network interface.\n func ipRouteAddDefault(request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Configure DNS resolver.\n func configureDns(request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Configure /etc/hosts.\n func configureHosts(request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Perform the sync syscall.\n func sync(request: Com_Apple_Containerization_Sandbox_V3_SyncRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Send a signal to a process via the PID.\n func kill(request: Com_Apple_Containerization_Sandbox_V3_KillRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextProvider {\n public var serviceName: Substring {\n return Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.serviceDescriptor.fullName[...]\n }\n\n /// Determines, calls and returns the appropriate request handler, depending on the request's method.\n /// Returns nil for methods not handled by this service.\n public func handle(\n method name: Substring,\n context: CallHandlerContext\n ) -> GRPCServerHandlerProtocol? {\n switch name {\n case \"Mount\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeMountInterceptors() ?? [],\n userFunction: self.mount(request:context:)\n )\n\n case \"Umount\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeUmountInterceptors() ?? [],\n userFunction: self.umount(request:context:)\n )\n\n case \"Setenv\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetenvInterceptors() ?? [],\n userFunction: self.setenv(request:context:)\n )\n\n case \"Getenv\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeGetenvInterceptors() ?? [],\n userFunction: self.getenv(request:context:)\n )\n\n case \"Mkdir\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeMkdirInterceptors() ?? [],\n userFunction: self.mkdir(request:context:)\n )\n\n case \"Sysctl\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSysctlInterceptors() ?? [],\n userFunction: self.sysctl(request:context:)\n )\n\n case \"SetTime\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetTimeInterceptors() ?? [],\n userFunction: self.setTime(request:context:)\n )\n\n case \"SetupEmulator\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetupEmulatorInterceptors() ?? [],\n userFunction: self.setupEmulator(request:context:)\n )\n\n case \"CreateProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCreateProcessInterceptors() ?? [],\n userFunction: self.createProcess(request:context:)\n )\n\n case \"DeleteProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeDeleteProcessInterceptors() ?? [],\n userFunction: self.deleteProcess(request:context:)\n )\n\n case \"StartProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeStartProcessInterceptors() ?? [],\n userFunction: self.startProcess(request:context:)\n )\n\n case \"KillProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeKillProcessInterceptors() ?? [],\n userFunction: self.killProcess(request:context:)\n )\n\n case \"WaitProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeWaitProcessInterceptors() ?? [],\n userFunction: self.waitProcess(request:context:)\n )\n\n case \"ResizeProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeResizeProcessInterceptors() ?? [],\n userFunction: self.resizeProcess(request:context:)\n )\n\n case \"CloseProcessStdin\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCloseProcessStdinInterceptors() ?? [],\n userFunction: self.closeProcessStdin(request:context:)\n )\n\n case \"ProxyVsock\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeProxyVsockInterceptors() ?? [],\n userFunction: self.proxyVsock(request:context:)\n )\n\n case \"StopVsockProxy\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeStopVsockProxyInterceptors() ?? [],\n userFunction: self.stopVsockProxy(request:context:)\n )\n\n case \"IpLinkSet\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpLinkSetInterceptors() ?? [],\n userFunction: self.ipLinkSet(request:context:)\n )\n\n case \"IpAddrAdd\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpAddrAddInterceptors() ?? [],\n userFunction: self.ipAddrAdd(request:context:)\n )\n\n case \"IpRouteAddLink\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpRouteAddLinkInterceptors() ?? [],\n userFunction: self.ipRouteAddLink(request:context:)\n )\n\n case \"IpRouteAddDefault\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpRouteAddDefaultInterceptors() ?? [],\n userFunction: self.ipRouteAddDefault(request:context:)\n )\n\n case \"ConfigureDns\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeConfigureDnsInterceptors() ?? [],\n userFunction: self.configureDns(request:context:)\n )\n\n case \"ConfigureHosts\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeConfigureHostsInterceptors() ?? [],\n userFunction: self.configureHosts(request:context:)\n )\n\n case \"Sync\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSyncInterceptors() ?? [],\n userFunction: self.sync(request:context:)\n )\n\n case \"Kill\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeKillInterceptors() ?? [],\n userFunction: self.kill(request:context:)\n )\n\n default:\n return nil\n }\n }\n}\n\n/// Context for interacting with a container's runtime environment.\n///\n/// To implement a server, implement an object which conforms to this protocol.\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncProvider: CallHandlerProvider, Sendable {\n static var serviceDescriptor: GRPCServiceDescriptor { get }\n var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextServerInterceptorFactoryProtocol? { get }\n\n /// Mount a filesystem.\n func mount(\n request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_MountResponse\n\n /// Unmount a filesystem.\n func umount(\n request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_UmountResponse\n\n /// Set an environment variable on the init process.\n func setenv(\n request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetenvResponse\n\n /// Get an environment variable from the init process.\n func getenv(\n request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_GetenvResponse\n\n /// Create a new directory inside the sandbox.\n func mkdir(\n request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_MkdirResponse\n\n /// Set sysctls in the context of the sandbox.\n func sysctl(\n request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SysctlResponse\n\n /// Set time in the guest.\n func setTime(\n request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetTimeResponse\n\n /// Set up an emulator in the guest for a specific binary format.\n func setupEmulator(\n request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse\n\n /// Create a new process inside the container.\n func createProcess(\n request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse\n\n /// Delete an existing process inside the container.\n func deleteProcess(\n request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse\n\n /// Start the provided process.\n func startProcess(\n request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StartProcessResponse\n\n /// Send a signal to the provided process.\n func killProcess(\n request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillProcessResponse\n\n /// Wait for a process to exit and return the exit code.\n func waitProcess(\n request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse\n\n /// Resize the tty of a given process. This will error if the process does\n /// not have a pty allocated.\n func resizeProcess(\n request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse\n\n /// Close IO for a given process.\n func closeProcessStdin(\n request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse\n\n /// Proxy a vsock port to a unix domain socket in the guest, or vice versa.\n func proxyVsock(\n request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse\n\n /// Stop a vsock proxy to a unix domain socket.\n func stopVsockProxy(\n request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse\n\n /// Set the link state of a network interface.\n func ipLinkSet(\n request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse\n\n /// Add an IPv4 address to a network interface.\n func ipAddrAdd(\n request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse\n\n /// Add an IP route for a network interface.\n func ipRouteAddLink(\n request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse\n\n /// Add an IP route for a network interface.\n func ipRouteAddDefault(\n request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse\n\n /// Configure DNS resolver.\n func configureDns(\n request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse\n\n /// Configure /etc/hosts.\n func configureHosts(\n request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse\n\n /// Perform the sync syscall.\n func sync(\n request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SyncResponse\n\n /// Send a signal to a process via the PID.\n func kill(\n request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillResponse\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncProvider {\n public static var serviceDescriptor: GRPCServiceDescriptor {\n return Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.serviceDescriptor\n }\n\n public var serviceName: Substring {\n return Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.serviceDescriptor.fullName[...]\n }\n\n public var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextServerInterceptorFactoryProtocol? {\n return nil\n }\n\n public func handle(\n method name: Substring,\n context: CallHandlerContext\n ) -> GRPCServerHandlerProtocol? {\n switch name {\n case \"Mount\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeMountInterceptors() ?? [],\n wrapping: { try await self.mount(request: $0, context: $1) }\n )\n\n case \"Umount\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeUmountInterceptors() ?? [],\n wrapping: { try await self.umount(request: $0, context: $1) }\n )\n\n case \"Setenv\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetenvInterceptors() ?? [],\n wrapping: { try await self.setenv(request: $0, context: $1) }\n )\n\n case \"Getenv\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeGetenvInterceptors() ?? [],\n wrapping: { try await self.getenv(request: $0, context: $1) }\n )\n\n case \"Mkdir\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeMkdirInterceptors() ?? [],\n wrapping: { try await self.mkdir(request: $0, context: $1) }\n )\n\n case \"Sysctl\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSysctlInterceptors() ?? [],\n wrapping: { try await self.sysctl(request: $0, context: $1) }\n )\n\n case \"SetTime\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetTimeInterceptors() ?? [],\n wrapping: { try await self.setTime(request: $0, context: $1) }\n )\n\n case \"SetupEmulator\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetupEmulatorInterceptors() ?? [],\n wrapping: { try await self.setupEmulator(request: $0, context: $1) }\n )\n\n case \"CreateProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCreateProcessInterceptors() ?? [],\n wrapping: { try await self.createProcess(request: $0, context: $1) }\n )\n\n case \"DeleteProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeDeleteProcessInterceptors() ?? [],\n wrapping: { try await self.deleteProcess(request: $0, context: $1) }\n )\n\n case \"StartProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeStartProcessInterceptors() ?? [],\n wrapping: { try await self.startProcess(request: $0, context: $1) }\n )\n\n case \"KillProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeKillProcessInterceptors() ?? [],\n wrapping: { try await self.killProcess(request: $0, context: $1) }\n )\n\n case \"WaitProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeWaitProcessInterceptors() ?? [],\n wrapping: { try await self.waitProcess(request: $0, context: $1) }\n )\n\n case \"ResizeProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeResizeProcessInterceptors() ?? [],\n wrapping: { try await self.resizeProcess(request: $0, context: $1) }\n )\n\n case \"CloseProcessStdin\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCloseProcessStdinInterceptors() ?? [],\n wrapping: { try await self.closeProcessStdin(request: $0, context: $1) }\n )\n\n case \"ProxyVsock\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeProxyVsockInterceptors() ?? [],\n wrapping: { try await self.proxyVsock(request: $0, context: $1) }\n )\n\n case \"StopVsockProxy\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeStopVsockProxyInterceptors() ?? [],\n wrapping: { try await self.stopVsockProxy(request: $0, context: $1) }\n )\n\n case \"IpLinkSet\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpLinkSetInterceptors() ?? [],\n wrapping: { try await self.ipLinkSet(request: $0, context: $1) }\n )\n\n case \"IpAddrAdd\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpAddrAddInterceptors() ?? [],\n wrapping: { try await self.ipAddrAdd(request: $0, context: $1) }\n )\n\n case \"IpRouteAddLink\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpRouteAddLinkInterceptors() ?? [],\n wrapping: { try await self.ipRouteAddLink(request: $0, context: $1) }\n )\n\n case \"IpRouteAddDefault\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpRouteAddDefaultInterceptors() ?? [],\n wrapping: { try await self.ipRouteAddDefault(request: $0, context: $1) }\n )\n\n case \"ConfigureDns\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeConfigureDnsInterceptors() ?? [],\n wrapping: { try await self.configureDns(request: $0, context: $1) }\n )\n\n case \"ConfigureHosts\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeConfigureHostsInterceptors() ?? [],\n wrapping: { try await self.configureHosts(request: $0, context: $1) }\n )\n\n case \"Sync\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSyncInterceptors() ?? [],\n wrapping: { try await self.sync(request: $0, context: $1) }\n )\n\n case \"Kill\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeKillInterceptors() ?? [],\n wrapping: { try await self.kill(request: $0, context: $1) }\n )\n\n default:\n return nil\n }\n }\n}\n\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextServerInterceptorFactoryProtocol: Sendable {\n\n /// - Returns: Interceptors to use when handling 'mount'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeMountInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'umount'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeUmountInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'setenv'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeSetenvInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'getenv'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeGetenvInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'mkdir'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeMkdirInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'sysctl'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeSysctlInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'setTime'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeSetTimeInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'setupEmulator'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeSetupEmulatorInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'createProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeCreateProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'deleteProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeDeleteProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'startProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeStartProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'killProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeKillProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'waitProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeWaitProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'resizeProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeResizeProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'closeProcessStdin'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeCloseProcessStdinInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'proxyVsock'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeProxyVsockInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'stopVsockProxy'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeStopVsockProxyInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'ipLinkSet'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeIpLinkSetInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'ipAddrAdd'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeIpAddrAddInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'ipRouteAddLink'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeIpRouteAddLinkInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'ipRouteAddDefault'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeIpRouteAddDefaultInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'configureDns'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeConfigureDnsInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'configureHosts'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeConfigureHostsInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'sync'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeSyncInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'kill'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeKillInterceptors() -> [ServerInterceptor]\n}\n\npublic enum Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata {\n public static let serviceDescriptor = GRPCServiceDescriptor(\n name: \"SandboxContext\",\n fullName: \"com.apple.containerization.sandbox.v3.SandboxContext\",\n methods: [\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.mount,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.umount,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.setenv,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.getenv,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.mkdir,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.sysctl,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.setTime,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.setupEmulator,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.createProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.deleteProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.startProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.killProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.waitProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.resizeProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.closeProcessStdin,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.proxyVsock,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.stopVsockProxy,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.ipLinkSet,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.ipAddrAdd,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.ipRouteAddLink,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.ipRouteAddDefault,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.configureDns,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.configureHosts,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.sync,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.kill,\n ]\n )\n\n public enum Methods {\n public static let mount = GRPCMethodDescriptor(\n name: \"Mount\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Mount\",\n type: GRPCCallType.unary\n )\n\n public static let umount = GRPCMethodDescriptor(\n name: \"Umount\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Umount\",\n type: GRPCCallType.unary\n )\n\n public static let setenv = GRPCMethodDescriptor(\n name: \"Setenv\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Setenv\",\n type: GRPCCallType.unary\n )\n\n public static let getenv = GRPCMethodDescriptor(\n name: \"Getenv\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Getenv\",\n type: GRPCCallType.unary\n )\n\n public static let mkdir = GRPCMethodDescriptor(\n name: \"Mkdir\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Mkdir\",\n type: GRPCCallType.unary\n )\n\n public static let sysctl = GRPCMethodDescriptor(\n name: \"Sysctl\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Sysctl\",\n type: GRPCCallType.unary\n )\n\n public static let setTime = GRPCMethodDescriptor(\n name: \"SetTime\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/SetTime\",\n type: GRPCCallType.unary\n )\n\n public static let setupEmulator = GRPCMethodDescriptor(\n name: \"SetupEmulator\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/SetupEmulator\",\n type: GRPCCallType.unary\n )\n\n public static let createProcess = GRPCMethodDescriptor(\n name: \"CreateProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/CreateProcess\",\n type: GRPCCallType.unary\n )\n\n public static let deleteProcess = GRPCMethodDescriptor(\n name: \"DeleteProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/DeleteProcess\",\n type: GRPCCallType.unary\n )\n\n public static let startProcess = GRPCMethodDescriptor(\n name: \"StartProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/StartProcess\",\n type: GRPCCallType.unary\n )\n\n public static let killProcess = GRPCMethodDescriptor(\n name: \"KillProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/KillProcess\",\n type: GRPCCallType.unary\n )\n\n public static let waitProcess = GRPCMethodDescriptor(\n name: \"WaitProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/WaitProcess\",\n type: GRPCCallType.unary\n )\n\n public static let resizeProcess = GRPCMethodDescriptor(\n name: \"ResizeProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ResizeProcess\",\n type: GRPCCallType.unary\n )\n\n public static let closeProcessStdin = GRPCMethodDescriptor(\n name: \"CloseProcessStdin\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/CloseProcessStdin\",\n type: GRPCCallType.unary\n )\n\n public static let proxyVsock = GRPCMethodDescriptor(\n name: \"ProxyVsock\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ProxyVsock\",\n type: GRPCCallType.unary\n )\n\n public static let stopVsockProxy = GRPCMethodDescriptor(\n name: \"StopVsockProxy\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/StopVsockProxy\",\n type: GRPCCallType.unary\n )\n\n public static let ipLinkSet = GRPCMethodDescriptor(\n name: \"IpLinkSet\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpLinkSet\",\n type: GRPCCallType.unary\n )\n\n public static let ipAddrAdd = GRPCMethodDescriptor(\n name: \"IpAddrAdd\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpAddrAdd\",\n type: GRPCCallType.unary\n )\n\n public static let ipRouteAddLink = GRPCMethodDescriptor(\n name: \"IpRouteAddLink\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpRouteAddLink\",\n type: GRPCCallType.unary\n )\n\n public static let ipRouteAddDefault = GRPCMethodDescriptor(\n name: \"IpRouteAddDefault\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpRouteAddDefault\",\n type: GRPCCallType.unary\n )\n\n public static let configureDns = GRPCMethodDescriptor(\n name: \"ConfigureDns\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ConfigureDns\",\n type: GRPCCallType.unary\n )\n\n public static let configureHosts = GRPCMethodDescriptor(\n name: \"ConfigureHosts\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ConfigureHosts\",\n type: GRPCCallType.unary\n )\n\n public static let sync = GRPCMethodDescriptor(\n name: \"Sync\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Sync\",\n type: GRPCCallType.unary\n )\n\n public static let kill = GRPCMethodDescriptor(\n name: \"Kill\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Kill\",\n type: GRPCCallType.unary\n )\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/KeychainHelper.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport ContainerizationOS\n\n/// Helper type to lookup registry related values in the macOS keychain.\npublic struct KeychainHelper: Sendable {\n private let id: String\n public init(id: String) {\n self.id = id\n }\n\n /// Lookup authorization data for a given registry domain.\n public func lookup(domain: String) throws -> Authentication {\n let kq = KeychainQuery()\n\n do {\n guard let fetched = try kq.get(id: self.id, host: domain) else {\n throw Self.Error.keyNotFound\n }\n return BasicAuthentication(\n username: fetched.account,\n password: fetched.data\n )\n } catch let err as KeychainQuery.Error {\n switch err {\n case .keyNotPresent(_):\n throw Self.Error.keyNotFound\n default:\n throw Self.Error.queryError(\"query failure: \\(String(describing: err))\")\n }\n }\n }\n\n /// Delete authorization data for a given domain from the keychain.\n public func delete(domain: String) throws {\n let kq = KeychainQuery()\n try kq.delete(id: self.id, host: domain)\n }\n\n /// Save authorization data for a given domain to the keychain.\n public func save(domain: String, username: String, password: String) throws {\n let kq = KeychainQuery()\n try kq.save(id: self.id, host: domain, user: username, token: password)\n }\n\n /// Prompt for authorization data for a given domain to be saved to the keychain.\n /// This will cause the current terminal to enter a password prompt state where\n /// key strokes are hidden.\n public func credentialPrompt(domain: String) throws -> Authentication {\n let username = try userPrompt(domain: domain)\n let password = try passwordPrompt()\n return BasicAuthentication(username: username, password: password)\n }\n\n /// Prompts the current stdin for a username entry and then returns the value.\n public func userPrompt(domain: String) throws -> String {\n print(\"Provide registry username \\(domain): \", terminator: \"\")\n guard let username = readLine() else {\n throw Self.Error.invalidInput\n }\n return username\n }\n\n /// Prompts the current stdin for a password entry and then returns the value.\n /// This will cause the current stdin (if it is a terminal) to hide keystrokes\n /// by disabling echo.\n public func passwordPrompt() throws -> String {\n print(\"Provide registry password: \", terminator: \"\")\n let console = try Terminal.current\n defer { console.tryReset() }\n try console.disableEcho()\n\n guard let password = readLine() else {\n throw Self.Error.invalidInput\n }\n return password\n }\n}\n\nextension KeychainHelper {\n /// `KeychainHelper` errors.\n public enum Error: Swift.Error {\n case keyNotFound\n case invalidInput\n case queryError(String)\n }\n}\n#endif\n"], ["/containerization/Sources/cctl/cctl+Utils.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\nextension Application {\n static func fetchImage(reference: String, store: ImageStore) async throws -> Containerization.Image {\n do {\n return try await store.get(reference: reference)\n } catch let error as ContainerizationError {\n if error.code == .notFound {\n return try await store.pull(reference: reference)\n }\n throw error\n }\n }\n\n static func parseKeyValuePairs(from items: [String]) -> [String: String] {\n var parsedLabels: [String: String] = [:]\n for item in items {\n let parts = item.split(separator: \"=\", maxSplits: 1)\n guard parts.count == 2 else {\n continue\n }\n let key = String(parts[0])\n let val = String(parts[1])\n parsedLabels[key] = val\n }\n return parsedLabels\n }\n}\n\nextension ContainerizationOCI.Platform {\n static var arm64: ContainerizationOCI.Platform {\n .init(arch: \"arm64\", os: \"linux\", variant: \"v8\")\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/URL+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// The `resolvingSymlinksInPath` method of the `URL` struct does not resolve the symlinks\n/// for directories under `/private` which include`tmp`, `var` and `etc`\n/// hence adding a method to build up on the existing `resolvingSymlinksInPath` that prepends `/private` to those paths\nextension URL {\n /// returns the unescaped absolutePath of a URL joined by separator\n func absolutePath(_ separator: String = \"/\") -> String {\n self.pathComponents\n .joined(separator: separator)\n .dropFirst(\"/\".count)\n .description\n }\n\n public func resolvingSymlinksInPathWithPrivate() -> URL {\n let url = self.resolvingSymlinksInPath()\n #if os(macOS)\n let parts = url.pathComponents\n if parts.count > 1 {\n if (parts.first == \"/\") && [\"tmp\", \"var\", \"etc\"].contains(parts[1]) {\n if let resolved = NSURL.fileURL(withPathComponents: [\"/\", \"private\"] + parts[1...]) {\n return resolved\n }\n }\n }\n #endif\n return url\n }\n\n public var isDirectory: Bool {\n (try? resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true\n }\n\n public var isSymlink: Bool {\n (try? resourceValues(forKeys: [.isSymbolicLinkKey]))?.isSymbolicLink == true\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/IPAddress.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Facilitates conversion between IPv4 address representations.\npublic struct IPv4Address: Codable, CustomStringConvertible, Equatable, Sendable {\n /// The address as a 32-bit integer.\n public let value: UInt32\n\n /// Create an address from a dotted-decimal string, such as \"192.168.64.10\".\n public init(_ fromString: String) throws {\n let split = fromString.components(separatedBy: \".\")\n if split.count != 4 {\n throw NetworkAddressError.invalidStringAddress(address: fromString)\n }\n\n var parsedValue: UInt32 = 0\n for index in 0..<4 {\n guard let octet = UInt8(split[index]) else {\n throw NetworkAddressError.invalidStringAddress(address: fromString)\n }\n parsedValue |= UInt32(octet) << ((3 - index) * 8)\n }\n\n value = parsedValue\n }\n\n /// Create an address from an array of four bytes in network order (big-endian),\n /// such as [192, 168, 64, 10].\n public init(fromNetworkBytes: [UInt8]) throws {\n guard fromNetworkBytes.count == 4 else {\n throw NetworkAddressError.invalidNetworkByteAddress(address: fromNetworkBytes)\n }\n\n value =\n (UInt32(fromNetworkBytes[0]) << 24)\n | (UInt32(fromNetworkBytes[1]) << 16)\n | (UInt32(fromNetworkBytes[2]) << 8)\n | UInt32(fromNetworkBytes[3])\n }\n\n /// Create an address from a 32-bit integer, such as 0xc0a8_400a.\n public init(fromValue: UInt32) {\n value = fromValue\n }\n\n /// Retrieve the address as an array of bytes in network byte order.\n public var networkBytes: [UInt8] {\n [\n UInt8((value >> 24) & 0xff),\n UInt8((value >> 16) & 0xff),\n UInt8((value >> 8) & 0xff),\n UInt8(value & 0xff),\n ]\n }\n\n /// Retrieve the address as a dotted decimal string.\n public var description: String {\n networkBytes.map(String.init).joined(separator: \".\")\n }\n\n /// Create the base IPv4 address for a network that contains this\n /// address and uses the specified subnet mask length.\n public func prefix(prefixLength: PrefixLength) -> IPv4Address {\n IPv4Address(fromValue: value & prefixLength.prefixMask32)\n }\n}\n\nextension IPv4Address {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n let text = try container.decode(String.self)\n try self.init(text)\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n try container.encode(self.description)\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/AsyncSignalHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Synchronization\n\n/// Async friendly wrapper around `DispatchSourceSignal`. Provides an `AsyncStream`\n/// interface to get notified of received signals.\npublic final class AsyncSignalHandler: Sendable {\n /// An async stream that returns the signal that was caught, if ever.\n public var signals: AsyncStream {\n let (stream, cont) = AsyncStream.makeStream(of: Int32.self)\n self.state.withLock {\n $0.conts.append(cont)\n }\n cont.onTermination = { @Sendable _ in\n self.cancel()\n }\n return stream\n }\n\n /// Cancel every AsyncStream of signals, as well as the underlying\n /// DispatchSignalSource's for each registered signal.\n public func cancel() {\n self.state.withLock {\n if $0.conts.isEmpty {\n return\n }\n\n for cont in $0.conts {\n cont.finish()\n }\n for source in $0.sources {\n source.cancel()\n }\n $0.conts.removeAll()\n $0.sources.removeAll()\n }\n }\n\n struct State: Sendable {\n var conts: [AsyncStream.Continuation] = []\n nonisolated(unsafe) var sources: [any DispatchSourceSignal] = []\n }\n\n // We keep a reference to the continuation object that is created for\n // our AsyncStream and tell our signal handler to yield a value to it\n // returning a value to the consumer\n private func handler(_ sig: Int32) {\n self.state.withLock {\n for cont in $0.conts {\n cont.yield(sig)\n }\n }\n }\n\n private let state: Mutex = .init(State())\n\n /// Create a new `AsyncSignalHandler` for the list of given signals `notify`.\n /// The default signal handlers for these signals are removed and async handlers\n /// added in their place. The async signal handlers that are installed simply\n /// yield to a stream if and when a signal is caught.\n public static func create(notify on: [Int32]) -> AsyncSignalHandler {\n let out = AsyncSignalHandler()\n var sources = [any DispatchSourceSignal]()\n for sig in on {\n signal(sig, SIG_IGN)\n let source = DispatchSource.makeSignalSource(signal: sig)\n source.setEventHandler {\n out.handler(sig)\n }\n source.resume()\n // Retain a reference to our signal sources so that they\n // do not go out of scope.\n sources.append(source)\n }\n out.state.withLock { $0.sources = sources }\n return out\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/ArchiveError.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CArchive\nimport Foundation\n\n/// An enumeration of the errors that can be thrown while interacting with an archive.\npublic enum ArchiveError: Error, CustomStringConvertible {\n case unableToCreateArchive\n case noUnderlyingArchive\n case noArchiveInCallback\n case noDelegateConfigured\n case delegateFreedBeforeCallback\n case unableToSetFormat(CInt, Format)\n case unableToAddFilter(CInt, Filter)\n case unableToWriteEntryHeader(CInt)\n case unableToWriteData(CLong)\n case unableToCloseArchive(CInt)\n case unableToOpenArchive(CInt)\n case unableToSetOption(CInt)\n case failedToSetLocale(locales: [String])\n case failedToGetProperty(String, URLResourceKey)\n case failedToDetectFilter\n case failedToDetectFormat\n case failedToExtractArchive(String)\n\n /// Description of the error\n public var description: String {\n switch self {\n case .unableToCreateArchive:\n return \"Unable to create an archive.\"\n case .noUnderlyingArchive:\n return \"No underlying archive was provided.\"\n case .noArchiveInCallback:\n return \"No archive was provided in the callback.\"\n case .noDelegateConfigured:\n return \"No delegate was configured.\"\n case .delegateFreedBeforeCallback:\n return \"The delegate was freed before the callback was invoked.\"\n case .unableToSetFormat(let code, let name):\n return \"Unable to set the archive format \\(name), code \\(code)\"\n case .unableToAddFilter(let code, let name):\n return \"Unable to set the archive filter \\(name), code \\(code)\"\n case .unableToWriteEntryHeader(let code):\n return \"Unable to write the entry header to the archive. Error code \\(code)\"\n case .unableToWriteData(let code):\n return \"Unable to write data to the archive. Error code \\(code)\"\n case .unableToCloseArchive(let code):\n return \"Unable to close the archive. Error code \\(code)\"\n case .unableToOpenArchive(let code):\n return \"Unable to open the archive. Error code \\(code)\"\n case .unableToSetOption(_):\n return \"Unable to set an option on the archive.\"\n case .failedToSetLocale(let locales):\n return \"Failed to set locale to \\(locales)\"\n case .failedToGetProperty(let path, let propertyName):\n return \"Failed to read property \\(propertyName) from file at path \\(path)\"\n case .failedToDetectFilter:\n return \"Failed to detect filter from archive.\"\n case .failedToDetectFormat:\n return \"Failed to detect format from archive.\"\n case .failedToExtractArchive(let reason):\n return \"Failed to extract archive: \\(reason)\"\n }\n }\n}\n\npublic struct LibArchiveError: Error {\n public let source: ArchiveError\n public let description: String\n}\n\nfunc wrap(_ f: @autoclosure () -> CInt, _ e: (CInt) -> ArchiveError, underlying: OpaquePointer? = nil) throws {\n let result = f()\n guard result == ARCHIVE_OK else {\n let error = e(result)\n guard let underlying = underlying,\n let description = archive_error_string(underlying).map(String.init(cString:))\n else {\n throw error\n }\n throw LibArchiveError(source: error, description: description)\n }\n}\n"], ["/containerization/Sources/Containerization/Kernel.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// An object representing a Linux kernel used to boot a virtual machine.\n/// In addition to a path to the kernel itself, this type stores relevant\n/// data such as the commandline to pass to the kernel, and init arguments.\npublic struct Kernel: Sendable, Codable {\n /// The command line arguments passed to the kernel on boot.\n public struct CommandLine: Sendable, Codable {\n public static let kernelDefaults = [\n \"console=hvc0\",\n \"tsc=reliable\",\n ]\n\n /// Adds the debug argument to the kernel commandline.\n mutating public func addDebug() {\n self.kernelArgs.append(\"debug\")\n }\n\n /// Adds a panic level to the kernel commandline.\n mutating public func addPanic(level: Int) {\n self.kernelArgs.append(\"panic=\\(level)\")\n }\n\n /// Additional kernel arguments.\n public var kernelArgs: [String]\n /// Additional arguments passed to the Initial Process / Agent.\n public var initArgs: [String]\n\n /// Initializes the kernel commandline using the mix of kernel arguments\n /// and init arguments.\n public init(\n kernelArgs: [String] = kernelDefaults,\n initArgs: [String] = []\n ) {\n self.kernelArgs = kernelArgs\n self.initArgs = initArgs\n }\n\n /// Initializes the kernel commandline to the defaults of Self.kernelDefaults,\n /// adds a debug and panic flag as instructed, and optionally a set of init\n /// process flags to supply to vminitd.\n public init(debug: Bool, panic: Int, initArgs: [String] = []) {\n var args = Self.kernelDefaults\n if debug {\n args.append(\"debug\")\n }\n args.append(\"panic=\\(panic)\")\n self.kernelArgs = args\n self.initArgs = initArgs\n }\n }\n\n /// Path on disk to the kernel binary.\n public var path: URL\n /// Platform for the kernel.\n public var platform: SystemPlatform\n /// Kernel and init process command line.\n public var commandLine: Self.CommandLine\n\n /// Kernel command line arguments.\n public var kernelArgs: [String] {\n self.commandLine.kernelArgs\n }\n\n /// Init process arguments.\n public var initArgs: [String] {\n self.commandLine.initArgs\n }\n\n public init(\n path: URL,\n platform: SystemPlatform,\n commandline: Self.CommandLine = CommandLine(debug: false, panic: 0)\n ) {\n self.path = path\n self.platform = platform\n self.commandLine = commandline\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/RegistryClient+Error.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport Foundation\nimport NIOHTTP1\n\nextension RegistryClient {\n /// `RegistryClient` errors.\n public enum Error: Swift.Error, CustomStringConvertible {\n case invalidStatus(url: String, HTTPResponseStatus, reason: String? = nil)\n\n /// Description of the errors.\n public var description: String {\n switch self {\n case .invalidStatus(let u, let response, let reason):\n return \"HTTP request to \\(u) failed with response: \\(response.description). Reason: \\(reason ?? \"Unknown\")\"\n }\n }\n }\n\n /// The container registry typically returns actionable failure reasons in the response body\n /// of the failing HTTP Request. This type models the structure of the error message.\n /// Reference: https://distribution.github.io/distribution/spec/api/#errors\n internal struct ErrorResponse: Codable {\n let errors: [RemoteError]\n\n internal struct RemoteError: Codable {\n let code: String\n let message: String\n let detail: String?\n }\n\n internal static func fromResponseBody(_ body: HTTPClientResponse.Body) async -> ErrorResponse? {\n guard var buffer = try? await body.collect(upTo: Int(1.mib())) else {\n return nil\n }\n guard let bytes = buffer.readBytes(length: buffer.readableBytes) else {\n return nil\n }\n let data = Data(bytes)\n guard let jsonError = try? JSONDecoder().decode(ErrorResponse.self, from: data) else {\n return nil\n }\n return jsonError\n }\n\n public var jsonString: String {\n let data = try? JSONEncoder().encode(self)\n guard let data else {\n return \"{}\"\n }\n return String(data: data, encoding: .utf8) ?? \"{}\"\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Socket/VsockType.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CShim\n\n#if canImport(Musl)\nimport Musl\n#elseif canImport(Glibc)\nimport Glibc\n#elseif canImport(Darwin)\nimport Darwin\n#else\n#error(\"VsockType not supported on this platform.\")\n#endif\n\n/// Vsock variant of `SocketType`.\npublic struct VsockType: SocketType, Sendable {\n public var domain: Int32 { AF_VSOCK }\n public var type: Int32 { _SOCK_STREAM }\n public var description: String {\n \"\\(cid):\\(port)\"\n }\n\n public static let anyCID: UInt32 = UInt32(bitPattern: -1)\n public static let hypervisorCID: UInt32 = 0x0\n // Supported on Linux 5.6+; otherwise, will need to use getLocalCID().\n public static let localCID: UInt32 = 0x1\n public static let hostCID: UInt32 = 0x2\n\n // socketFD is unused on Linux.\n public static func getLocalCID(socketFD: Int32) throws -> UInt32 {\n let request = VsockLocalCIDIoctl\n #if os(Linux)\n let fd = open(\"/dev/vsock\", O_RDONLY | O_CLOEXEC)\n if fd == -1 {\n throw Socket.errnoToError(msg: \"failed to open /dev/vsock\")\n }\n defer { close(fd) }\n #else\n let fd = socketFD\n #endif\n var cid: UInt32 = 0\n guard sysIoctl(fd, numericCast(request), &cid) != -1 else {\n throw Socket.errnoToError(msg: \"failed to get local cid\")\n }\n return cid\n }\n\n public let port: UInt32\n public let cid: UInt32\n\n private let _addr: sockaddr_vm\n\n public init(port: UInt32, cid: UInt32) {\n self.cid = cid\n self.port = port\n var sockaddr = sockaddr_vm()\n sockaddr.svm_family = sa_family_t(AF_VSOCK)\n sockaddr.svm_cid = cid\n sockaddr.svm_port = port\n self._addr = sockaddr\n }\n\n private init(sockaddr: sockaddr_vm) {\n self._addr = sockaddr\n self.cid = sockaddr.svm_cid\n self.port = sockaddr.svm_port\n }\n\n public func accept(fd: Int32) throws -> (Int32, SocketType) {\n var clientFD: Int32 = -1\n var addr = sockaddr_vm()\n\n while clientFD < 0 {\n var size = socklen_t(MemoryLayout.stride)\n clientFD = withUnsafeMutablePointer(to: &addr) { pointer in\n pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { pointer in\n sysAccept(fd, pointer, &size)\n }\n }\n if clientFD < 0 && errno != EINTR {\n throw Socket.errnoToError(msg: \"accept failed\")\n }\n }\n return (clientFD, VsockType(sockaddr: addr))\n }\n\n public func withSockAddr(_ closure: (UnsafePointer, UInt32) throws -> Void) throws {\n var addr = self._addr\n try withUnsafePointer(to: &addr) {\n let addrBytes = UnsafeRawPointer($0).assumingMemoryBound(to: sockaddr.self)\n try closure(addrBytes, UInt32(MemoryLayout.stride))\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/Timeout.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// `Timeout` contains helpers to run an operation and error out if\n/// the operation does not finish within a provided time.\npublic struct Timeout {\n /// Performs the passed in `operation` and throws a `CancellationError` if the operation\n /// doesn't finish in the provided `seconds` amount.\n public static func run(\n seconds: UInt32,\n operation: @escaping @Sendable () async -> T\n ) async throws -> T {\n try await withThrowingTaskGroup(of: T.self) { group in\n group.addTask {\n await operation()\n }\n\n group.addTask {\n try await Task.sleep(for: .seconds(seconds))\n throw CancellationError()\n }\n\n guard let result = try await group.next() else {\n fatalError()\n }\n\n group.cancelAll()\n return result\n }\n }\n}\n"], ["/containerization/Sources/Containerization/VirtualMachineAgent.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\n/// A protocol for the agent running inside a virtual machine. If an operation isn't\n/// supported the implementation MUST return a ContainerizationError with a code of\n/// `.unsupported`.\npublic protocol VirtualMachineAgent: Sendable {\n /// Perform a platform specific standard setup\n /// of the runtime environment.\n func standardSetup() async throws\n /// Close any resources held by the agent.\n func close() async throws\n\n // POSIX\n func getenv(key: String) async throws -> String\n func setenv(key: String, value: String) async throws\n func mount(_ mount: ContainerizationOCI.Mount) async throws\n func umount(path: String, flags: Int32) async throws\n func mkdir(path: String, all: Bool, perms: UInt32) async throws\n @discardableResult\n func kill(pid: Int32, signal: Int32) async throws -> Int32\n\n // Process lifecycle\n func createProcess(\n id: String,\n containerID: String?,\n stdinPort: UInt32?,\n stdoutPort: UInt32?,\n stderrPort: UInt32?,\n configuration: ContainerizationOCI.Spec,\n options: Data?\n ) async throws\n func startProcess(id: String, containerID: String?) async throws -> Int32\n func signalProcess(id: String, containerID: String?, signal: Int32) async throws\n func resizeProcess(id: String, containerID: String?, columns: UInt32, rows: UInt32) async throws\n func waitProcess(id: String, containerID: String?, timeoutInSeconds: Int64?) async throws -> Int32\n func deleteProcess(id: String, containerID: String?) async throws\n func closeProcessStdin(id: String, containerID: String?) async throws\n\n // Networking\n func up(name: String, mtu: UInt32?) async throws\n func down(name: String) async throws\n func addressAdd(name: String, address: String) async throws\n func routeAddDefault(name: String, gateway: String) async throws\n func configureDNS(config: DNS, location: String) async throws\n func configureHosts(config: Hosts, location: String) async throws\n}\n\nextension VirtualMachineAgent {\n public func closeProcessStdin(id: String, containerID: String?) async throws {\n throw ContainerizationError(.unsupported, message: \"closeProcessStdin\")\n }\n\n public func configureHosts(config: Hosts, location: String) async throws {\n throw ContainerizationError(.unsupported, message: \"configureHosts\")\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/CIDRAddress.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Describes an IPv4 CIDR address block.\npublic struct CIDRAddress: CustomStringConvertible, Equatable, Sendable {\n\n /// The base IPv4 address of the CIDR block.\n public let lower: IPv4Address\n\n /// The last IPv4 address of the CIDR block\n public let upper: IPv4Address\n\n /// The IPv4 address component of the CIDR block.\n public let address: IPv4Address\n\n /// The address prefix length for the CIDR block, which determines its size.\n public let prefixLength: PrefixLength\n\n /// Create an CIDR address block from its text representation.\n public init(_ cidr: String) throws {\n let split = cidr.components(separatedBy: \"/\")\n guard split.count == 2 else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n address = try IPv4Address(split[0])\n guard let prefixLength = PrefixLength(split[1]) else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n guard prefixLength >= 0 && prefixLength <= 32 else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n\n self.prefixLength = prefixLength\n lower = address.prefix(prefixLength: prefixLength)\n upper = IPv4Address(fromValue: lower.value + prefixLength.suffixMask32)\n }\n\n /// Create a CIDR address from a member IP and a prefix length.\n public init(_ address: IPv4Address, prefixLength: PrefixLength) throws {\n guard prefixLength >= 0 && prefixLength <= 32 else {\n throw NetworkAddressError.invalidCIDR(cidr: \"\\(address)/\\(prefixLength)\")\n }\n\n self.prefixLength = prefixLength\n self.address = address\n lower = address.prefix(prefixLength: prefixLength)\n upper = IPv4Address(fromValue: lower.value + prefixLength.suffixMask32)\n }\n\n /// Create the smallest CIDR block that includes the lower and upper bounds.\n public init(lower: IPv4Address, upper: IPv4Address) throws {\n guard lower.value <= upper.value else {\n throw NetworkAddressError.invalidAddressRange(lower: lower.description, upper: upper.description)\n }\n\n address = lower\n for prefixLength: PrefixLength in 1...32 {\n // find the first case where a subnet mask would put lower and upper in different CIDR block\n let mask = prefixLength.prefixMask32\n\n if (lower.value & mask) != (upper.value & mask) {\n self.prefixLength = prefixLength - 1\n self.lower = address.prefix(prefixLength: self.prefixLength)\n self.upper = IPv4Address(fromValue: self.lower.value + self.prefixLength.suffixMask32)\n return\n }\n }\n\n // if lower and upper are same, create a /32 block\n self.prefixLength = 32\n self.lower = lower\n self.upper = upper\n }\n\n /// Get the offset of the specified address, relative to the\n /// base address for the CIDR block, returning nil if the block\n /// does not contain the address.\n public func getIndex(_ address: IPv4Address) -> UInt32? {\n guard address.value >= lower.value && address.value <= upper.value else {\n return nil\n }\n\n return address.value - lower.value\n }\n\n /// Return true if the CIDR block contains the specified address.\n public func contains(ipv4: IPv4Address) -> Bool {\n lower.value <= ipv4.value && ipv4.value <= upper.value\n }\n\n /// Return true if the CIDR block contains all addresses of another CIDR block.\n public func contains(cidr: CIDRAddress) -> Bool {\n lower.value <= cidr.lower.value && cidr.upper.value <= upper.value\n }\n\n /// Return true if the CIDR block shares any addresses with another CIDR block.\n public func overlaps(cidr: CIDRAddress) -> Bool {\n (lower.value <= cidr.lower.value && upper.value >= cidr.lower.value)\n || (upper.value >= cidr.upper.value && lower.value <= cidr.upper.value)\n }\n\n /// Retrieve the text representation of the CIDR block.\n public var description: String {\n \"\\(address)/\\(prefixLength)\"\n }\n}\n\nextension CIDRAddress: Codable {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n let text = try container.decode(String.self)\n try self.init(text)\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n try container.encode(self.description)\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Signals.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Helper type with utilities to parse and manipulate unix signals.\npublic struct Signals {\n /// Returns the numeric values of all known signals.\n public static func allNumeric() -> [Int32] {\n Array(Signals.all.values)\n }\n\n /// Parses a string representation of a signal (SIGKILL) and returns\n // the 32 bit integer representation (9).\n public static func parseSignal(_ signal: String) throws -> Int32 {\n if let sig = Int32(signal) {\n if !Signals.all.values.contains(sig) {\n throw Error.invalidSignal(signal)\n }\n return sig\n }\n var signalUpper = signal.uppercased()\n signalUpper.trimPrefix(\"SIG\")\n guard let sig = Signals.all[signalUpper] else {\n throw Error.invalidSignal(signal)\n }\n return sig\n }\n\n /// Errors that can be encountered for converting signals.\n public enum Error: Swift.Error, CustomStringConvertible {\n case invalidSignal(String)\n\n public var description: String {\n switch self {\n case .invalidSignal(let sig):\n return \"invalid signal: \\(sig)\"\n }\n }\n }\n}\n\n#if os(macOS)\n\nextension Signals {\n /// `all` returns all signals for the current platform.\n public static let all: [String: Int32] = [\n \"ABRT\": SIGABRT,\n \"ALRM\": SIGALRM,\n \"BUS\": SIGBUS,\n \"CHLD\": SIGCHLD,\n \"CONT\": SIGCONT,\n \"EMT\": SIGEMT,\n \"FPE\": SIGFPE,\n \"HUP\": SIGHUP,\n \"ILL\": SIGILL,\n \"INFO\": SIGINFO,\n \"INT\": SIGINT,\n \"IO\": SIGIO,\n \"IOT\": SIGIOT,\n \"KILL\": SIGKILL,\n \"PIPE\": SIGPIPE,\n \"PROF\": SIGPROF,\n \"QUIT\": SIGQUIT,\n \"SEGV\": SIGSEGV,\n \"STOP\": SIGSTOP,\n \"SYS\": SIGSYS,\n \"TERM\": SIGTERM,\n \"TRAP\": SIGTRAP,\n \"TSTP\": SIGTSTP,\n \"TTIN\": SIGTTIN,\n \"TTOU\": SIGTTOU,\n \"URG\": SIGURG,\n \"USR1\": SIGUSR1,\n \"USR2\": SIGUSR2,\n \"VTALRM\": SIGVTALRM,\n \"WINCH\": SIGWINCH,\n \"XCPU\": SIGXCPU,\n \"XFSZ\": SIGXFSZ,\n ]\n}\n\n#endif\n\n#if os(Linux)\n\nextension Signals {\n /// `all` returns all signals for the current platform.\n ///\n /// For Linux this isn't actually exhaustive as it excludes\n /// rtmin/rtmax entries.\n public static let all: [String: Int32] = [\n \"ABRT\": SIGABRT,\n \"ALRM\": SIGALRM,\n \"BUS\": SIGBUS,\n \"CHLD\": SIGCHLD,\n \"CLD\": SIGCHLD,\n \"CONT\": SIGCONT,\n \"FPE\": SIGFPE,\n \"HUP\": SIGHUP,\n \"ILL\": SIGILL,\n \"INT\": SIGINT,\n \"IO\": SIGIO,\n \"IOT\": SIGIOT,\n \"KILL\": SIGKILL,\n \"PIPE\": SIGPIPE,\n \"POLL\": SIGPOLL,\n \"PROF\": SIGPROF,\n \"PWR\": SIGPWR,\n \"QUIT\": SIGQUIT,\n \"SEGV\": SIGSEGV,\n \"STKFLT\": SIGSTKFLT,\n \"STOP\": SIGSTOP,\n \"SYS\": SIGSYS,\n \"TERM\": SIGTERM,\n \"TRAP\": SIGTRAP,\n \"TSTP\": SIGTSTP,\n \"TTIN\": SIGTTIN,\n \"TTOU\": SIGTTOU,\n \"URG\": SIGURG,\n \"USR1\": SIGUSR1,\n \"USR2\": SIGUSR2,\n \"VTALRM\": SIGVTALRM,\n \"WINCH\": SIGWINCH,\n \"XCPU\": SIGXCPU,\n \"XFSZ\": SIGXFSZ,\n ]\n}\n\n#endif\n"], ["/containerization/Sources/ContainerizationEXT4/FilePath+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\nextension FilePath {\n public static let Separator: String = \"/\"\n\n public var bytes: [UInt8] {\n self.withCString { cstr in\n var ptr = cstr\n var rawBytes: [UInt8] = []\n while UInt(bitPattern: ptr) != 0 {\n if ptr.pointee == 0x00 { break }\n rawBytes.append(UInt8(bitPattern: ptr.pointee))\n ptr = ptr.successor()\n }\n return rawBytes\n }\n }\n\n public var base: String {\n self.lastComponent?.string ?? \"/\"\n }\n\n public var dir: FilePath {\n self.removingLastComponent()\n }\n\n public var url: URL {\n URL(fileURLWithPath: self.string)\n }\n\n public var items: [String] {\n self.components.map { $0.string }\n }\n\n public init(_ url: URL) {\n self.init(url.path(percentEncoded: false))\n }\n\n public init?(_ data: Data) {\n let cstr: String? = data.withUnsafeBytes { (rbp: UnsafeRawBufferPointer) in\n guard let baseAddress = rbp.baseAddress else {\n return nil\n }\n\n let cString = baseAddress.bindMemory(to: CChar.self, capacity: data.count)\n return String(cString: cString)\n }\n\n guard let cstr else {\n return nil\n }\n self.init(cstr)\n }\n\n public func join(_ path: FilePath) -> FilePath {\n self.pushing(path)\n }\n\n public func join(_ path: String) -> FilePath {\n self.join(FilePath(path))\n }\n\n public func split() -> (dir: FilePath, base: String) {\n (self.dir, self.base)\n }\n\n public func clean() -> FilePath {\n self.lexicallyNormalized()\n }\n\n public static func rel(_ basepath: String, _ targpath: String) -> FilePath {\n let base = FilePath(basepath)\n let targ = FilePath(targpath)\n\n if base == targ {\n return \".\"\n }\n\n let baseComponents = base.items\n let targComponents = targ.items\n\n var commonPrefix = 0\n while commonPrefix < min(baseComponents.count, targComponents.count)\n && baseComponents[commonPrefix] == targComponents[commonPrefix]\n {\n commonPrefix += 1\n }\n\n let upCount = baseComponents.count - commonPrefix\n let relComponents = Array(repeating: \"..\", count: upCount) + targComponents[commonPrefix...]\n\n return FilePath(relComponents.joined(separator: Self.Separator))\n }\n}\n\nextension FileHandle {\n public convenience init?(forWritingTo path: FilePath) {\n self.init(forWritingAtPath: path.description)\n }\n\n public convenience init?(forReadingAtPath path: FilePath) {\n self.init(forReadingAtPath: path.description)\n }\n\n public convenience init?(forReadingFrom path: FilePath) {\n self.init(forReadingAtPath: path.description)\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/TerminalIO.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport Synchronization\n\nfinal class TerminalIO: ManagedProcess.IO & Sendable {\n private struct State {\n var stdin: IOPair?\n var stdout: IOPair?\n }\n\n private let parent: Terminal\n private let child: Terminal\n private let log: Logger?\n private let hostStdio: HostStdio\n private let state: Mutex\n\n init(\n stdio: HostStdio,\n log: Logger?\n ) throws {\n let pair = try Terminal.create()\n self.parent = pair.parent\n self.child = pair.child\n self.state = Mutex(State())\n self.hostStdio = stdio\n self.log = log\n }\n\n func resize(size: Terminal.Size) throws {\n try parent.resize(size: size)\n }\n\n func start(process: inout Command) throws {\n try self.state.withLock {\n let ptyHandle = self.child.handle\n let useHandles = self.hostStdio.stdin != nil || self.hostStdio.stdout != nil\n // We currently set stdin to the controlling terminal always, so\n // it must be a valid pty descriptor.\n process.stdin = useHandles ? ptyHandle : nil\n\n let stdoutHandle = useHandles ? ptyHandle : nil\n process.stdout = stdoutHandle\n process.stderr = stdoutHandle\n\n if let stdinPort = self.hostStdio.stdin {\n let type = VsockType(\n port: stdinPort,\n cid: VsockType.hostCID\n )\n let stdinSocket = try Socket(type: type, closeOnDeinit: false)\n try stdinSocket.connect()\n\n let pair = IOPair(\n readFrom: stdinSocket,\n writeTo: self.parent.handle,\n logger: self.log\n )\n $0.stdin = pair\n\n try pair.relay()\n }\n\n if let stdoutPort = self.hostStdio.stdout {\n let type = VsockType(\n port: stdoutPort,\n cid: VsockType.hostCID\n )\n let stdoutSocket = try Socket(type: type, closeOnDeinit: false)\n try stdoutSocket.connect()\n\n let pair = IOPair(\n readFrom: self.parent.handle,\n writeTo: stdoutSocket,\n logger: self.log\n )\n $0.stdout = pair\n\n try pair.relay()\n }\n }\n }\n\n func closeStdin() throws {\n self.state.withLock {\n $0.stdin?.close()\n }\n }\n\n func closeAfterExec() throws {\n try child.close()\n }\n}\n"], ["/containerization/Sources/Containerization/DNSConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// DNS configuration for a container. The values will be used to\n/// construct /etc/resolv.conf for a given container.\npublic struct DNS: Sendable {\n /// The set of default nameservers to use if none are provided\n /// in the constructor.\n public static let defaultNameservers = [\"1.1.1.1\"]\n\n /// The nameservers a container should use.\n public var nameservers: [String]\n /// The DNS domain to use.\n public var domain: String?\n /// The DNS search domains to use.\n public var searchDomains: [String]\n /// The DNS options to use.\n public var options: [String]\n\n public init(\n nameservers: [String] = defaultNameservers,\n domain: String? = nil,\n searchDomains: [String] = [],\n options: [String] = []\n ) {\n self.nameservers = nameservers\n self.domain = domain\n self.searchDomains = searchDomains\n self.options = options\n }\n}\n\nextension DNS {\n public var resolvConf: String {\n var text = \"\"\n\n if !nameservers.isEmpty {\n text += nameservers.map { \"nameserver \\($0)\" }.joined(separator: \"\\n\") + \"\\n\"\n }\n\n if let domain {\n text += \"domain \\(domain)\\n\"\n }\n\n if !searchDomains.isEmpty {\n text += \"search \\(searchDomains.joined(separator: \" \"))\\n\"\n }\n\n if !options.isEmpty {\n text += \"opts \\(options.joined(separator: \" \"))\\n\"\n }\n\n return text\n }\n}\n"], ["/containerization/Sources/Containerization/Agent/Vminitd+Rosetta.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\n\nextension Vminitd {\n /// Enable Rosetta's x86_64 emulation.\n public func enableRosetta() async throws {\n let path = \"/run/rosetta\"\n try await self.mount(\n .init(\n type: \"virtiofs\",\n source: \"rosetta\",\n destination: path\n )\n )\n try await self.setupEmulator(\n binaryPath: \"\\(path)/rosetta\",\n configuration: Binfmt.Entry.amd64()\n )\n }\n}\n"], ["/containerization/Sources/Containerization/SandboxContext/SandboxContext.pb.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// DO NOT EDIT.\n// swift-format-ignore-file\n// swiftlint:disable all\n//\n// Generated by the Swift generator plugin for the protocol buffer compiler.\n// Source: SandboxContext.proto\n//\n// For information on using the generated types, please see the documentation:\n// https://github.com/apple/swift-protobuf/\n\nimport Foundation\nimport SwiftProtobuf\n\n// If the compiler emits an error on this type, it is because this file\n// was generated by a version of the `protoc` Swift plug-in that is\n// incompatible with the version of SwiftProtobuf to which you are linking.\n// Please ensure that you are building against the same version of the API\n// that was used to generate this file.\nfileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {\n struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}\n typealias Version = _2\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_Stdio: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var stdinPort: Int32 {\n get {return _stdinPort ?? 0}\n set {_stdinPort = newValue}\n }\n /// Returns true if `stdinPort` has been explicitly set.\n public var hasStdinPort: Bool {return self._stdinPort != nil}\n /// Clears the value of `stdinPort`. Subsequent reads from it will return its default value.\n public mutating func clearStdinPort() {self._stdinPort = nil}\n\n public var stdoutPort: Int32 {\n get {return _stdoutPort ?? 0}\n set {_stdoutPort = newValue}\n }\n /// Returns true if `stdoutPort` has been explicitly set.\n public var hasStdoutPort: Bool {return self._stdoutPort != nil}\n /// Clears the value of `stdoutPort`. Subsequent reads from it will return its default value.\n public mutating func clearStdoutPort() {self._stdoutPort = nil}\n\n public var stderrPort: Int32 {\n get {return _stderrPort ?? 0}\n set {_stderrPort = newValue}\n }\n /// Returns true if `stderrPort` has been explicitly set.\n public var hasStderrPort: Bool {return self._stderrPort != nil}\n /// Clears the value of `stderrPort`. Subsequent reads from it will return its default value.\n public mutating func clearStderrPort() {self._stderrPort = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _stdinPort: Int32? = nil\n fileprivate var _stdoutPort: Int32? = nil\n fileprivate var _stderrPort: Int32? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var binaryPath: String = String()\n\n public var name: String = String()\n\n public var type: String = String()\n\n public var offset: String = String()\n\n public var magic: String = String()\n\n public var mask: String = String()\n\n public var flags: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetTimeRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var sec: Int64 = 0\n\n public var usec: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetTimeResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SysctlRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var settings: Dictionary = [:]\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SysctlResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var vsockPort: UInt32 = 0\n\n public var guestPath: String = String()\n\n public var guestSocketPermissions: UInt32 {\n get {return _guestSocketPermissions ?? 0}\n set {_guestSocketPermissions = newValue}\n }\n /// Returns true if `guestSocketPermissions` has been explicitly set.\n public var hasGuestSocketPermissions: Bool {return self._guestSocketPermissions != nil}\n /// Clears the value of `guestSocketPermissions`. Subsequent reads from it will return its default value.\n public mutating func clearGuestSocketPermissions() {self._guestSocketPermissions = nil}\n\n public var action: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest.Action = .into\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public enum Action: SwiftProtobuf.Enum, Swift.CaseIterable {\n public typealias RawValue = Int\n case into // = 0\n case outOf // = 1\n case UNRECOGNIZED(Int)\n\n public init() {\n self = .into\n }\n\n public init?(rawValue: Int) {\n switch rawValue {\n case 0: self = .into\n case 1: self = .outOf\n default: self = .UNRECOGNIZED(rawValue)\n }\n }\n\n public var rawValue: Int {\n switch self {\n case .into: return 0\n case .outOf: return 1\n case .UNRECOGNIZED(let i): return i\n }\n }\n\n // The compiler won't synthesize support with the UNRECOGNIZED case.\n public static let allCases: [Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest.Action] = [\n .into,\n .outOf,\n ]\n\n }\n\n public init() {}\n\n fileprivate var _guestSocketPermissions: UInt32? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_MountRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var type: String = String()\n\n public var source: String = String()\n\n public var destination: String = String()\n\n public var options: [String] = []\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_MountResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_UmountRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var path: String = String()\n\n public var flags: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_UmountResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetenvRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var key: String = String()\n\n public var value: String {\n get {return _value ?? String()}\n set {_value = newValue}\n }\n /// Returns true if `value` has been explicitly set.\n public var hasValue: Bool {return self._value != nil}\n /// Clears the value of `value`. Subsequent reads from it will return its default value.\n public mutating func clearValue() {self._value = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _value: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetenvResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_GetenvRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var key: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_GetenvResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var value: String {\n get {return _value ?? String()}\n set {_value = newValue}\n }\n /// Returns true if `value` has been explicitly set.\n public var hasValue: Bool {return self._value != nil}\n /// Clears the value of `value`. Subsequent reads from it will return its default value.\n public mutating func clearValue() {self._value = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _value: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var stdin: UInt32 {\n get {return _stdin ?? 0}\n set {_stdin = newValue}\n }\n /// Returns true if `stdin` has been explicitly set.\n public var hasStdin: Bool {return self._stdin != nil}\n /// Clears the value of `stdin`. Subsequent reads from it will return its default value.\n public mutating func clearStdin() {self._stdin = nil}\n\n public var stdout: UInt32 {\n get {return _stdout ?? 0}\n set {_stdout = newValue}\n }\n /// Returns true if `stdout` has been explicitly set.\n public var hasStdout: Bool {return self._stdout != nil}\n /// Clears the value of `stdout`. Subsequent reads from it will return its default value.\n public mutating func clearStdout() {self._stdout = nil}\n\n public var stderr: UInt32 {\n get {return _stderr ?? 0}\n set {_stderr = newValue}\n }\n /// Returns true if `stderr` has been explicitly set.\n public var hasStderr: Bool {return self._stderr != nil}\n /// Clears the value of `stderr`. Subsequent reads from it will return its default value.\n public mutating func clearStderr() {self._stderr = nil}\n\n public var configuration: Data = Data()\n\n public var options: Data {\n get {return _options ?? Data()}\n set {_options = newValue}\n }\n /// Returns true if `options` has been explicitly set.\n public var hasOptions: Bool {return self._options != nil}\n /// Clears the value of `options`. Subsequent reads from it will return its default value.\n public mutating func clearOptions() {self._options = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n fileprivate var _stdin: UInt32? = nil\n fileprivate var _stdout: UInt32? = nil\n fileprivate var _stderr: UInt32? = nil\n fileprivate var _options: Data? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var exitCode: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var rows: UInt32 = 0\n\n public var columns: UInt32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_StartProcessRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_StartProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var pid: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_KillProcessRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var signal: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_KillProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var result: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_MkdirRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var path: String = String()\n\n public var all: Bool = false\n\n public var perms: UInt32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_MkdirResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var interface: String = String()\n\n public var up: Bool = false\n\n public var mtu: UInt32 {\n get {return _mtu ?? 0}\n set {_mtu = newValue}\n }\n /// Returns true if `mtu` has been explicitly set.\n public var hasMtu: Bool {return self._mtu != nil}\n /// Clears the value of `mtu`. Subsequent reads from it will return its default value.\n public mutating func clearMtu() {self._mtu = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _mtu: UInt32? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var interface: String = String()\n\n public var address: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var interface: String = String()\n\n public var address: String = String()\n\n public var srcAddr: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var interface: String = String()\n\n public var gateway: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var location: String = String()\n\n public var nameservers: [String] = []\n\n public var domain: String {\n get {return _domain ?? String()}\n set {_domain = newValue}\n }\n /// Returns true if `domain` has been explicitly set.\n public var hasDomain: Bool {return self._domain != nil}\n /// Clears the value of `domain`. Subsequent reads from it will return its default value.\n public mutating func clearDomain() {self._domain = nil}\n\n public var searchDomains: [String] = []\n\n public var options: [String] = []\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _domain: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var location: String = String()\n\n public var entries: [Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.HostsEntry] = []\n\n public var comment: String {\n get {return _comment ?? String()}\n set {_comment = newValue}\n }\n /// Returns true if `comment` has been explicitly set.\n public var hasComment: Bool {return self._comment != nil}\n /// Clears the value of `comment`. Subsequent reads from it will return its default value.\n public mutating func clearComment() {self._comment = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public struct HostsEntry: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var ipAddress: String = String()\n\n public var hostnames: [String] = []\n\n public var comment: String {\n get {return _comment ?? String()}\n set {_comment = newValue}\n }\n /// Returns true if `comment` has been explicitly set.\n public var hasComment: Bool {return self._comment != nil}\n /// Clears the value of `comment`. Subsequent reads from it will return its default value.\n public mutating func clearComment() {self._comment = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _comment: String? = nil\n }\n\n public init() {}\n\n fileprivate var _comment: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SyncRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SyncResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_KillRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var pid: Int32 = 0\n\n public var signal: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_KillResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var result: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\n// MARK: - Code below here is support for the SwiftProtobuf runtime.\n\nfileprivate let _protobuf_package = \"com.apple.containerization.sandbox.v3\"\n\nextension Com_Apple_Containerization_Sandbox_V3_Stdio: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Stdio\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"stdinPort\"),\n 2: .same(proto: \"stdoutPort\"),\n 3: .same(proto: \"stderrPort\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self._stdinPort) }()\n case 2: try { try decoder.decodeSingularInt32Field(value: &self._stdoutPort) }()\n case 3: try { try decoder.decodeSingularInt32Field(value: &self._stderrPort) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n try { if let v = self._stdinPort {\n try visitor.visitSingularInt32Field(value: v, fieldNumber: 1)\n } }()\n try { if let v = self._stdoutPort {\n try visitor.visitSingularInt32Field(value: v, fieldNumber: 2)\n } }()\n try { if let v = self._stderrPort {\n try visitor.visitSingularInt32Field(value: v, fieldNumber: 3)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_Stdio, rhs: Com_Apple_Containerization_Sandbox_V3_Stdio) -> Bool {\n if lhs._stdinPort != rhs._stdinPort {return false}\n if lhs._stdoutPort != rhs._stdoutPort {return false}\n if lhs._stderrPort != rhs._stderrPort {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetupEmulatorRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"binary_path\"),\n 2: .same(proto: \"name\"),\n 3: .same(proto: \"type\"),\n 4: .same(proto: \"offset\"),\n 5: .same(proto: \"magic\"),\n 6: .same(proto: \"mask\"),\n 7: .same(proto: \"flags\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.binaryPath) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.name) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.type) }()\n case 4: try { try decoder.decodeSingularStringField(value: &self.offset) }()\n case 5: try { try decoder.decodeSingularStringField(value: &self.magic) }()\n case 6: try { try decoder.decodeSingularStringField(value: &self.mask) }()\n case 7: try { try decoder.decodeSingularStringField(value: &self.flags) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.binaryPath.isEmpty {\n try visitor.visitSingularStringField(value: self.binaryPath, fieldNumber: 1)\n }\n if !self.name.isEmpty {\n try visitor.visitSingularStringField(value: self.name, fieldNumber: 2)\n }\n if !self.type.isEmpty {\n try visitor.visitSingularStringField(value: self.type, fieldNumber: 3)\n }\n if !self.offset.isEmpty {\n try visitor.visitSingularStringField(value: self.offset, fieldNumber: 4)\n }\n if !self.magic.isEmpty {\n try visitor.visitSingularStringField(value: self.magic, fieldNumber: 5)\n }\n if !self.mask.isEmpty {\n try visitor.visitSingularStringField(value: self.mask, fieldNumber: 6)\n }\n if !self.flags.isEmpty {\n try visitor.visitSingularStringField(value: self.flags, fieldNumber: 7)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest, rhs: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest) -> Bool {\n if lhs.binaryPath != rhs.binaryPath {return false}\n if lhs.name != rhs.name {return false}\n if lhs.type != rhs.type {return false}\n if lhs.offset != rhs.offset {return false}\n if lhs.magic != rhs.magic {return false}\n if lhs.mask != rhs.mask {return false}\n if lhs.flags != rhs.flags {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetupEmulatorResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse, rhs: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetTimeRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetTimeRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"sec\"),\n 2: .same(proto: \"usec\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt64Field(value: &self.sec) }()\n case 2: try { try decoder.decodeSingularInt32Field(value: &self.usec) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.sec != 0 {\n try visitor.visitSingularInt64Field(value: self.sec, fieldNumber: 1)\n }\n if self.usec != 0 {\n try visitor.visitSingularInt32Field(value: self.usec, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest, rhs: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest) -> Bool {\n if lhs.sec != rhs.sec {return false}\n if lhs.usec != rhs.usec {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetTimeResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetTimeResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetTimeResponse, rhs: Com_Apple_Containerization_Sandbox_V3_SetTimeResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SysctlRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SysctlRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"settings\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.settings) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.settings.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.settings, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SysctlRequest, rhs: Com_Apple_Containerization_Sandbox_V3_SysctlRequest) -> Bool {\n if lhs.settings != rhs.settings {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SysctlResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SysctlResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SysctlResponse, rhs: Com_Apple_Containerization_Sandbox_V3_SysctlResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ProxyVsockRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .standard(proto: \"vsock_port\"),\n 3: .same(proto: \"guestPath\"),\n 4: .same(proto: \"guestSocketPermissions\"),\n 5: .same(proto: \"action\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularUInt32Field(value: &self.vsockPort) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.guestPath) }()\n case 4: try { try decoder.decodeSingularUInt32Field(value: &self._guestSocketPermissions) }()\n case 5: try { try decoder.decodeSingularEnumField(value: &self.action) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n if self.vsockPort != 0 {\n try visitor.visitSingularUInt32Field(value: self.vsockPort, fieldNumber: 2)\n }\n if !self.guestPath.isEmpty {\n try visitor.visitSingularStringField(value: self.guestPath, fieldNumber: 3)\n }\n try { if let v = self._guestSocketPermissions {\n try visitor.visitSingularUInt32Field(value: v, fieldNumber: 4)\n } }()\n if self.action != .into {\n try visitor.visitSingularEnumField(value: self.action, fieldNumber: 5)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest, rhs: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.vsockPort != rhs.vsockPort {return false}\n if lhs.guestPath != rhs.guestPath {return false}\n if lhs._guestSocketPermissions != rhs._guestSocketPermissions {return false}\n if lhs.action != rhs.action {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest.Action: SwiftProtobuf._ProtoNameProviding {\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 0: .same(proto: \"INTO\"),\n 1: .same(proto: \"OUT_OF\"),\n ]\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ProxyVsockResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse, rhs: Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".StopVsockProxyRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest, rhs: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".StopVsockProxyResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse, rhs: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_MountRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".MountRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"type\"),\n 2: .same(proto: \"source\"),\n 3: .same(proto: \"destination\"),\n 4: .same(proto: \"options\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.type) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.source) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.destination) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.options) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.type.isEmpty {\n try visitor.visitSingularStringField(value: self.type, fieldNumber: 1)\n }\n if !self.source.isEmpty {\n try visitor.visitSingularStringField(value: self.source, fieldNumber: 2)\n }\n if !self.destination.isEmpty {\n try visitor.visitSingularStringField(value: self.destination, fieldNumber: 3)\n }\n if !self.options.isEmpty {\n try visitor.visitRepeatedStringField(value: self.options, fieldNumber: 4)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_MountRequest, rhs: Com_Apple_Containerization_Sandbox_V3_MountRequest) -> Bool {\n if lhs.type != rhs.type {return false}\n if lhs.source != rhs.source {return false}\n if lhs.destination != rhs.destination {return false}\n if lhs.options != rhs.options {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_MountResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".MountResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_MountResponse, rhs: Com_Apple_Containerization_Sandbox_V3_MountResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_UmountRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".UmountRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"path\"),\n 2: .same(proto: \"flags\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.path) }()\n case 2: try { try decoder.decodeSingularInt32Field(value: &self.flags) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.path.isEmpty {\n try visitor.visitSingularStringField(value: self.path, fieldNumber: 1)\n }\n if self.flags != 0 {\n try visitor.visitSingularInt32Field(value: self.flags, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_UmountRequest, rhs: Com_Apple_Containerization_Sandbox_V3_UmountRequest) -> Bool {\n if lhs.path != rhs.path {return false}\n if lhs.flags != rhs.flags {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_UmountResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".UmountResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_UmountResponse, rhs: Com_Apple_Containerization_Sandbox_V3_UmountResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetenvRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetenvRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"key\"),\n 2: .same(proto: \"value\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.key) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._value) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.key.isEmpty {\n try visitor.visitSingularStringField(value: self.key, fieldNumber: 1)\n }\n try { if let v = self._value {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetenvRequest, rhs: Com_Apple_Containerization_Sandbox_V3_SetenvRequest) -> Bool {\n if lhs.key != rhs.key {return false}\n if lhs._value != rhs._value {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetenvResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetenvResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetenvResponse, rhs: Com_Apple_Containerization_Sandbox_V3_SetenvResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_GetenvRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".GetenvRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"key\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.key) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.key.isEmpty {\n try visitor.visitSingularStringField(value: self.key, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_GetenvRequest, rhs: Com_Apple_Containerization_Sandbox_V3_GetenvRequest) -> Bool {\n if lhs.key != rhs.key {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_GetenvResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".GetenvResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"value\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self._value) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n try { if let v = self._value {\n try visitor.visitSingularStringField(value: v, fieldNumber: 1)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_GetenvResponse, rhs: Com_Apple_Containerization_Sandbox_V3_GetenvResponse) -> Bool {\n if lhs._value != rhs._value {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CreateProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n 3: .same(proto: \"stdin\"),\n 4: .same(proto: \"stdout\"),\n 5: .same(proto: \"stderr\"),\n 6: .same(proto: \"configuration\"),\n 7: .same(proto: \"options\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n case 3: try { try decoder.decodeSingularUInt32Field(value: &self._stdin) }()\n case 4: try { try decoder.decodeSingularUInt32Field(value: &self._stdout) }()\n case 5: try { try decoder.decodeSingularUInt32Field(value: &self._stderr) }()\n case 6: try { try decoder.decodeSingularBytesField(value: &self.configuration) }()\n case 7: try { try decoder.decodeSingularBytesField(value: &self._options) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try { if let v = self._stdin {\n try visitor.visitSingularUInt32Field(value: v, fieldNumber: 3)\n } }()\n try { if let v = self._stdout {\n try visitor.visitSingularUInt32Field(value: v, fieldNumber: 4)\n } }()\n try { if let v = self._stderr {\n try visitor.visitSingularUInt32Field(value: v, fieldNumber: 5)\n } }()\n if !self.configuration.isEmpty {\n try visitor.visitSingularBytesField(value: self.configuration, fieldNumber: 6)\n }\n try { if let v = self._options {\n try visitor.visitSingularBytesField(value: v, fieldNumber: 7)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs._stdin != rhs._stdin {return false}\n if lhs._stdout != rhs._stdout {return false}\n if lhs._stderr != rhs._stderr {return false}\n if lhs.configuration != rhs.configuration {return false}\n if lhs._options != rhs._options {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CreateProcessResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".WaitProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".WaitProcessResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"exitCode\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.exitCode) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.exitCode != 0 {\n try visitor.visitSingularInt32Field(value: self.exitCode, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse) -> Bool {\n if lhs.exitCode != rhs.exitCode {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ResizeProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n 3: .same(proto: \"rows\"),\n 4: .same(proto: \"columns\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n case 3: try { try decoder.decodeSingularUInt32Field(value: &self.rows) }()\n case 4: try { try decoder.decodeSingularUInt32Field(value: &self.columns) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n if self.rows != 0 {\n try visitor.visitSingularUInt32Field(value: self.rows, fieldNumber: 3)\n }\n if self.columns != 0 {\n try visitor.visitSingularUInt32Field(value: self.columns, fieldNumber: 4)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.rows != rhs.rows {return false}\n if lhs.columns != rhs.columns {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ResizeProcessResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".DeleteProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".DeleteProcessResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_StartProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".StartProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_StartProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".StartProcessResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"pid\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.pid) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.pid != 0 {\n try visitor.visitSingularInt32Field(value: self.pid, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_StartProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_StartProcessResponse) -> Bool {\n if lhs.pid != rhs.pid {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_KillProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".KillProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n 3: .same(proto: \"signal\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n case 3: try { try decoder.decodeSingularInt32Field(value: &self.signal) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n if self.signal != 0 {\n try visitor.visitSingularInt32Field(value: self.signal, fieldNumber: 3)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.signal != rhs.signal {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_KillProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".KillProcessResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"result\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.result) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.result != 0 {\n try visitor.visitSingularInt32Field(value: self.result, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_KillProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_KillProcessResponse) -> Bool {\n if lhs.result != rhs.result {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CloseProcessStdinRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest, rhs: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CloseProcessStdinResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse, rhs: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_MkdirRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".MkdirRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"path\"),\n 2: .same(proto: \"all\"),\n 3: .same(proto: \"perms\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.path) }()\n case 2: try { try decoder.decodeSingularBoolField(value: &self.all) }()\n case 3: try { try decoder.decodeSingularUInt32Field(value: &self.perms) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.path.isEmpty {\n try visitor.visitSingularStringField(value: self.path, fieldNumber: 1)\n }\n if self.all != false {\n try visitor.visitSingularBoolField(value: self.all, fieldNumber: 2)\n }\n if self.perms != 0 {\n try visitor.visitSingularUInt32Field(value: self.perms, fieldNumber: 3)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_MkdirRequest, rhs: Com_Apple_Containerization_Sandbox_V3_MkdirRequest) -> Bool {\n if lhs.path != rhs.path {return false}\n if lhs.all != rhs.all {return false}\n if lhs.perms != rhs.perms {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_MkdirResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".MkdirResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_MkdirResponse, rhs: Com_Apple_Containerization_Sandbox_V3_MkdirResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpLinkSetRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"interface\"),\n 2: .same(proto: \"up\"),\n 3: .same(proto: \"mtu\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.interface) }()\n case 2: try { try decoder.decodeSingularBoolField(value: &self.up) }()\n case 3: try { try decoder.decodeSingularUInt32Field(value: &self._mtu) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.interface.isEmpty {\n try visitor.visitSingularStringField(value: self.interface, fieldNumber: 1)\n }\n if self.up != false {\n try visitor.visitSingularBoolField(value: self.up, fieldNumber: 2)\n }\n try { if let v = self._mtu {\n try visitor.visitSingularUInt32Field(value: v, fieldNumber: 3)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest, rhs: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest) -> Bool {\n if lhs.interface != rhs.interface {return false}\n if lhs.up != rhs.up {return false}\n if lhs._mtu != rhs._mtu {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpLinkSetResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse, rhs: Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpAddrAddRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"interface\"),\n 2: .same(proto: \"address\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.interface) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.address) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.interface.isEmpty {\n try visitor.visitSingularStringField(value: self.interface, fieldNumber: 1)\n }\n if !self.address.isEmpty {\n try visitor.visitSingularStringField(value: self.address, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest, rhs: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest) -> Bool {\n if lhs.interface != rhs.interface {return false}\n if lhs.address != rhs.address {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpAddrAddResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse, rhs: Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpRouteAddLinkRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"interface\"),\n 2: .same(proto: \"address\"),\n 3: .same(proto: \"srcAddr\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.interface) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.address) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.srcAddr) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.interface.isEmpty {\n try visitor.visitSingularStringField(value: self.interface, fieldNumber: 1)\n }\n if !self.address.isEmpty {\n try visitor.visitSingularStringField(value: self.address, fieldNumber: 2)\n }\n if !self.srcAddr.isEmpty {\n try visitor.visitSingularStringField(value: self.srcAddr, fieldNumber: 3)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest, rhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest) -> Bool {\n if lhs.interface != rhs.interface {return false}\n if lhs.address != rhs.address {return false}\n if lhs.srcAddr != rhs.srcAddr {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpRouteAddLinkResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse, rhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpRouteAddDefaultRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"interface\"),\n 2: .same(proto: \"gateway\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.interface) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.gateway) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.interface.isEmpty {\n try visitor.visitSingularStringField(value: self.interface, fieldNumber: 1)\n }\n if !self.gateway.isEmpty {\n try visitor.visitSingularStringField(value: self.gateway, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest, rhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest) -> Bool {\n if lhs.interface != rhs.interface {return false}\n if lhs.gateway != rhs.gateway {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpRouteAddDefaultResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse, rhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ConfigureDnsRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"location\"),\n 2: .same(proto: \"nameservers\"),\n 3: .same(proto: \"domain\"),\n 4: .same(proto: \"searchDomains\"),\n 5: .same(proto: \"options\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.location) }()\n case 2: try { try decoder.decodeRepeatedStringField(value: &self.nameservers) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self._domain) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.searchDomains) }()\n case 5: try { try decoder.decodeRepeatedStringField(value: &self.options) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.location.isEmpty {\n try visitor.visitSingularStringField(value: self.location, fieldNumber: 1)\n }\n if !self.nameservers.isEmpty {\n try visitor.visitRepeatedStringField(value: self.nameservers, fieldNumber: 2)\n }\n try { if let v = self._domain {\n try visitor.visitSingularStringField(value: v, fieldNumber: 3)\n } }()\n if !self.searchDomains.isEmpty {\n try visitor.visitRepeatedStringField(value: self.searchDomains, fieldNumber: 4)\n }\n if !self.options.isEmpty {\n try visitor.visitRepeatedStringField(value: self.options, fieldNumber: 5)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest, rhs: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest) -> Bool {\n if lhs.location != rhs.location {return false}\n if lhs.nameservers != rhs.nameservers {return false}\n if lhs._domain != rhs._domain {return false}\n if lhs.searchDomains != rhs.searchDomains {return false}\n if lhs.options != rhs.options {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ConfigureDnsResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse, rhs: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ConfigureHostsRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"location\"),\n 2: .same(proto: \"entries\"),\n 3: .same(proto: \"comment\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.location) }()\n case 2: try { try decoder.decodeRepeatedMessageField(value: &self.entries) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self._comment) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.location.isEmpty {\n try visitor.visitSingularStringField(value: self.location, fieldNumber: 1)\n }\n if !self.entries.isEmpty {\n try visitor.visitRepeatedMessageField(value: self.entries, fieldNumber: 2)\n }\n try { if let v = self._comment {\n try visitor.visitSingularStringField(value: v, fieldNumber: 3)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest, rhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest) -> Bool {\n if lhs.location != rhs.location {return false}\n if lhs.entries != rhs.entries {return false}\n if lhs._comment != rhs._comment {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.HostsEntry: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.protoMessageName + \".HostsEntry\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"ipAddress\"),\n 2: .same(proto: \"hostnames\"),\n 3: .same(proto: \"comment\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.ipAddress) }()\n case 2: try { try decoder.decodeRepeatedStringField(value: &self.hostnames) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self._comment) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.ipAddress.isEmpty {\n try visitor.visitSingularStringField(value: self.ipAddress, fieldNumber: 1)\n }\n if !self.hostnames.isEmpty {\n try visitor.visitRepeatedStringField(value: self.hostnames, fieldNumber: 2)\n }\n try { if let v = self._comment {\n try visitor.visitSingularStringField(value: v, fieldNumber: 3)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.HostsEntry, rhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.HostsEntry) -> Bool {\n if lhs.ipAddress != rhs.ipAddress {return false}\n if lhs.hostnames != rhs.hostnames {return false}\n if lhs._comment != rhs._comment {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ConfigureHostsResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse, rhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SyncRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SyncRequest\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SyncRequest, rhs: Com_Apple_Containerization_Sandbox_V3_SyncRequest) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SyncResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SyncResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SyncResponse, rhs: Com_Apple_Containerization_Sandbox_V3_SyncResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_KillRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".KillRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"pid\"),\n 3: .same(proto: \"signal\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.pid) }()\n case 3: try { try decoder.decodeSingularInt32Field(value: &self.signal) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.pid != 0 {\n try visitor.visitSingularInt32Field(value: self.pid, fieldNumber: 1)\n }\n if self.signal != 0 {\n try visitor.visitSingularInt32Field(value: self.signal, fieldNumber: 3)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_KillRequest, rhs: Com_Apple_Containerization_Sandbox_V3_KillRequest) -> Bool {\n if lhs.pid != rhs.pid {return false}\n if lhs.signal != rhs.signal {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_KillResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".KillResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"result\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.result) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.result != 0 {\n try visitor.visitSingularInt32Field(value: self.result, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_KillResponse, rhs: Com_Apple_Containerization_Sandbox_V3_KillResponse) -> Bool {\n if lhs.result != rhs.result {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/ContentWriter.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Crypto\nimport Foundation\nimport NIOCore\n\n/// Provides a context to write data into a directory.\npublic class ContentWriter {\n private let base: URL\n private let encoder = JSONEncoder()\n\n /// Create a new ContentWriter.\n /// - Parameters:\n /// - base: The URL to write content to. If this is not a directory a\n /// ContainerizationError will be thrown with a code of .internalError.\n public init(for base: URL) throws {\n self.encoder.outputFormatting = [JSONEncoder.OutputFormatting.sortedKeys]\n\n self.base = base\n var isDirectory = ObjCBool(true)\n let exists = FileManager.default.fileExists(atPath: base.path, isDirectory: &isDirectory)\n\n guard exists && isDirectory.boolValue else {\n throw ContainerizationError(.internalError, message: \"Cannot create ContentWriter for path \\(base.absolutePath()). Not a directory\")\n }\n }\n\n /// Writes the data blob to the base URL provided in the constructor.\n /// - Parameters:\n /// - data: The data blob to write to a file under the base path.\n @discardableResult\n public func write(_ data: Data) throws -> (size: Int64, digest: SHA256.Digest) {\n let digest = SHA256.hash(data: data)\n let destination = base.appendingPathComponent(digest.encoded)\n try data.write(to: destination)\n return (Int64(data.count), digest)\n }\n\n /// Reads the data present in the passed in URL and writes it to the base path.\n /// - Parameters:\n /// - url: The URL to read the data from.\n @discardableResult\n public func create(from url: URL) throws -> (size: Int64, digest: SHA256.Digest) {\n let data = try Data(contentsOf: url)\n return try self.write(data)\n }\n\n /// Encodes the passed in type as a JSON blob and writes it to the base path.\n /// - Parameters:\n /// - content: The type to convert to JSON.\n @discardableResult\n public func create(from content: T) throws -> (size: Int64, digest: SHA256.Digest) {\n let data = try self.encoder.encode(content)\n return try self.write(data)\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/RotatingAddressAllocator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Synchronization\n\npackage final class RotatingAddressAllocator: AddressAllocator {\n package typealias AddressType = UInt32\n\n private struct State {\n var allocations: [AddressType]\n var enabled: Bool\n var allocationCount: Int\n let addressToIndex: AddressToIndexTransform\n let indexToAddress: IndexToAddressTransform\n\n init(\n size: UInt32,\n addressToIndex: @escaping AddressToIndexTransform,\n indexToAddress: @escaping IndexToAddressTransform\n ) {\n self.allocations = [UInt32](0..\n\n /// Create an allocator with specified size and index mappings.\n package init(\n size: UInt32,\n addressToIndex: @escaping AddressToIndexTransform,\n indexToAddress: @escaping IndexToAddressTransform\n ) {\n let state = State(\n size: size,\n addressToIndex: addressToIndex,\n indexToAddress: indexToAddress\n )\n self.stateGuard = Mutex(state)\n }\n\n public func allocate() throws -> AddressType {\n try self.stateGuard.withLock { state in\n guard state.enabled else {\n throw AllocatorError.allocatorDisabled\n }\n\n guard state.allocations.count > 0 else {\n throw AllocatorError.allocatorFull\n }\n\n let value = state.allocations.removeFirst()\n\n guard let address = state.indexToAddress(Int(value)) else {\n throw AllocatorError.invalidIndex(Int(value))\n }\n\n state.allocationCount += 1\n return address\n }\n }\n\n package func reserve(_ address: AddressType) throws {\n try self.stateGuard.withLock { state in\n guard state.enabled else {\n throw AllocatorError.allocatorDisabled\n }\n\n guard let index = state.addressToIndex(address) else {\n throw AllocatorError.invalidAddress(address.description)\n }\n\n let i = state.allocations.firstIndex(of: UInt32(index))\n guard let i else {\n throw AllocatorError.alreadyAllocated(\"\\(address.description)\")\n }\n\n _ = state.allocations.remove(at: i)\n state.allocationCount += 1\n }\n }\n\n package func release(_ address: AddressType) throws {\n try self.stateGuard.withLock { state in\n guard let index = (state.addressToIndex(address)) else {\n throw AllocatorError.invalidAddress(address.description)\n }\n let value = UInt32(index)\n\n guard !state.allocations.contains(value) else {\n throw AllocatorError.notAllocated(\"\\(address.description)\")\n }\n\n state.allocations.append(value)\n state.allocationCount -= 1\n }\n }\n\n package func disableAllocator() -> Bool {\n self.stateGuard.withLock { state in\n guard state.allocationCount == 0 else {\n return false\n }\n state.enabled = false\n return true\n }\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/OSFile+Splice.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension OSFile {\n struct SpliceFile: Sendable {\n var file: OSFile\n var offset: Int\n let pipe = Pipe()\n\n var fileDescriptor: Int32 {\n file.fileDescriptor\n }\n\n var reader: Int32 {\n pipe.fileHandleForReading.fileDescriptor\n }\n\n var writer: Int32 {\n pipe.fileHandleForWriting.fileDescriptor\n }\n\n init(fd: Int32) {\n self.file = OSFile(fd: fd)\n self.offset = 0\n }\n\n init(handle: FileHandle) {\n self.file = OSFile(handle: handle)\n self.offset = 0\n }\n\n init(from: OSFile, withOffset: Int = 0) {\n self.file = from\n self.offset = withOffset\n }\n\n func close() throws {\n try self.file.close()\n }\n }\n\n static func splice(from: inout SpliceFile, to: inout SpliceFile, count: Int = 1 << 16) throws -> (read: Int, wrote: Int, action: IOAction) {\n let fromOffset = from.offset\n let toOffset = to.offset\n\n while true {\n while (from.offset - to.offset) < count {\n let toRead = count - (from.offset - to.offset)\n let bytesRead = Foundation.splice(from.fileDescriptor, nil, to.writer, nil, toRead, UInt32(bitPattern: SPLICE_F_MOVE | SPLICE_F_NONBLOCK))\n if bytesRead == -1 {\n if errno != EAGAIN && errno != EIO {\n throw POSIXError(.init(rawValue: errno)!)\n }\n break\n }\n if bytesRead == 0 {\n return (0, 0, .eof)\n }\n from.offset += bytesRead\n if bytesRead < toRead {\n break\n }\n }\n if from.offset == to.offset {\n return (from.offset - fromOffset, to.offset - toOffset, .success)\n }\n while to.offset < from.offset {\n let toWrite = from.offset - to.offset\n let bytesWrote = Foundation.splice(to.reader, nil, to.fileDescriptor, nil, toWrite, UInt32(bitPattern: SPLICE_F_MOVE | SPLICE_F_NONBLOCK))\n if bytesWrote == -1 {\n if errno != EAGAIN && errno != EIO {\n throw POSIXError(.init(rawValue: errno)!)\n }\n break\n }\n to.offset += bytesWrote\n if bytesWrote == 0 {\n return (from.offset - fromOffset, to.offset - toOffset, .brokenPipe)\n }\n if bytesWrote < toWrite {\n break\n }\n }\n }\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/OSFile.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nstruct OSFile: Sendable {\n private let fd: Int32\n\n enum IOAction: Equatable {\n case eof\n case again\n case success\n case brokenPipe\n case error(_ errno: Int32)\n }\n\n var closed: Bool {\n Foundation.fcntl(fd, F_GETFD) == -1 && errno == EBADF\n }\n\n var fileDescriptor: Int32 { fd }\n\n init(fd: Int32) {\n self.fd = fd\n }\n\n init(handle: FileHandle) {\n self.fd = handle.fileDescriptor\n }\n\n func close() throws {\n guard Foundation.close(self.fd) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n }\n\n func read(_ buffer: UnsafeMutableBufferPointer) -> (read: Int, action: IOAction) {\n if buffer.count == 0 {\n return (0, .success)\n }\n\n var bytesRead: Int = 0\n while true {\n let n = Foundation.read(\n self.fd,\n buffer.baseAddress!.advanced(by: bytesRead),\n buffer.count - bytesRead\n )\n if n == -1 {\n if errno == EAGAIN || errno == EIO {\n return (bytesRead, .again)\n }\n return (bytesRead, .error(errno))\n }\n\n if n == 0 {\n return (bytesRead, .eof)\n }\n\n bytesRead += n\n if bytesRead < buffer.count {\n continue\n }\n return (bytesRead, .success)\n }\n }\n\n func write(_ buffer: UnsafeMutableBufferPointer) -> (wrote: Int, action: IOAction) {\n if buffer.count == 0 {\n return (0, .success)\n }\n\n var bytesWrote: Int = 0\n while true {\n let n = Foundation.write(\n self.fd,\n buffer.baseAddress!.advanced(by: bytesWrote),\n buffer.count - bytesWrote\n )\n if n == -1 {\n if errno == EAGAIN || errno == EIO {\n return (bytesWrote, .again)\n }\n return (bytesWrote, .error(errno))\n }\n\n if n == 0 {\n return (bytesWrote, .brokenPipe)\n }\n\n bytesWrote += n\n if bytesWrote < buffer.count {\n continue\n }\n return (bytesWrote, .success)\n }\n }\n\n static func pipe() -> (read: Self, write: Self) {\n let pipe = Pipe()\n return (Self(handle: pipe.fileHandleForReading), Self(handle: pipe.fileHandleForWriting))\n }\n\n static func open(path: String) throws -> Self {\n try open(path: path, mode: O_RDONLY | O_CLOEXEC)\n }\n\n static func open(path: String, mode: Int32) throws -> Self {\n let fd = Foundation.open(path, mode)\n if fd < 0 {\n throw POSIXError(.init(rawValue: errno)!)\n }\n return Self(fd: fd)\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/NetworkAddress+Allocator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension IPv4Address {\n /// Creates an allocator for IPv4 addresses.\n public static func allocator(lower: UInt32, size: Int) throws -> any AddressAllocator {\n // NOTE: 2^31 - 1 size limit in the very improbable case that we run on 32-bit.\n guard size > 0 && size < Int.max && 0xffff_ffff - lower >= size - 1 else {\n throw AllocatorError.rangeExceeded\n }\n return IndexedAddressAllocator(\n size: size,\n addressToIndex: { address in\n guard address.value >= lower && address.value - lower <= UInt32(size) else {\n return nil\n }\n return Int(address.value - lower)\n },\n indexToAddress: { IPv4Address(fromValue: lower + UInt32($0)) }\n )\n }\n}\n\nextension UInt16 {\n /// Creates an allocator for TCP/UDP ports and other UInt16 values.\n public static func allocator(lower: UInt16, size: Int) throws -> any AddressAllocator {\n guard 0xffff - lower + 1 >= size else {\n throw AllocatorError.rangeExceeded\n }\n\n return IndexedAddressAllocator(\n size: size,\n addressToIndex: { address in\n guard address >= lower && address <= lower + UInt16(size) else {\n return nil\n }\n return Int(address - lower)\n },\n indexToAddress: { lower + UInt16($0) }\n )\n }\n}\n\nextension UInt32 {\n /// Creates an allocator for vsock ports, or any UInt32 values.\n public static func allocator(lower: UInt32, size: Int) throws -> any AddressAllocator {\n guard 0xffff_ffff - lower + 1 >= size else {\n throw AllocatorError.rangeExceeded\n }\n\n return IndexedAddressAllocator(\n size: size,\n addressToIndex: { address in\n guard address >= lower && address <= lower + UInt32(size) else {\n return nil\n }\n return Int(address - lower)\n },\n indexToAddress: { lower + UInt32($0) }\n )\n }\n\n /// Creates a rotating allocator for vsock ports, or any UInt32 values.\n public static func rotatingAllocator(lower: UInt32, size: UInt32) throws -> any AddressAllocator {\n guard 0xffff_ffff - lower + 1 >= size else {\n throw AllocatorError.rangeExceeded\n }\n\n return RotatingAddressAllocator(\n size: size,\n addressToIndex: { address in\n guard address >= lower && address <= lower + UInt32(size) else {\n return nil\n }\n return Int(address - lower)\n },\n indexToAddress: { lower + UInt32($0) }\n )\n }\n}\n\nextension Character {\n private static let deviceLetters = Array(\"abcdefghijklmnopqrstuvwxyz\")\n\n /// Creates an allocator for block device tags, or any character values.\n public static func blockDeviceTagAllocator() -> any AddressAllocator {\n IndexedAddressAllocator(\n size: Self.deviceLetters.count,\n addressToIndex: { address in\n Self.deviceLetters.firstIndex(of: address)\n },\n indexToAddress: { Self.deviceLetters[$0] }\n )\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/StandardIO.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport Synchronization\n\nfinal class StandardIO: ManagedProcess.IO & Sendable {\n private struct State {\n var stdin: IOPair?\n var stdout: IOPair?\n var stderr: IOPair?\n\n var stdinPipe: Pipe?\n var stdoutPipe: Pipe?\n var stderrPipe: Pipe?\n }\n\n private let log: Logger?\n private let hostStdio: HostStdio\n private let state: Mutex\n\n init(\n stdio: HostStdio,\n log: Logger?\n ) {\n self.hostStdio = stdio\n self.log = log\n self.state = Mutex(State())\n }\n\n func start(process: inout Command) throws {\n try self.state.withLock {\n if let stdinPort = self.hostStdio.stdin {\n let inPipe = Pipe()\n process.stdin = inPipe.fileHandleForReading\n $0.stdinPipe = inPipe\n\n let type = VsockType(\n port: stdinPort,\n cid: VsockType.hostCID\n )\n let stdinSocket = try Socket(type: type, closeOnDeinit: false)\n try stdinSocket.connect()\n\n let pair = IOPair(\n readFrom: stdinSocket,\n writeTo: inPipe.fileHandleForWriting,\n logger: log\n )\n $0.stdin = pair\n\n try pair.relay()\n }\n\n if let stdoutPort = self.hostStdio.stdout {\n let outPipe = Pipe()\n process.stdout = outPipe.fileHandleForWriting\n $0.stdoutPipe = outPipe\n\n let type = VsockType(\n port: stdoutPort,\n cid: VsockType.hostCID\n )\n let stdoutSocket = try Socket(type: type, closeOnDeinit: false)\n try stdoutSocket.connect()\n\n let pair = IOPair(\n readFrom: outPipe.fileHandleForReading,\n writeTo: stdoutSocket,\n logger: log\n )\n $0.stdout = pair\n\n try pair.relay()\n }\n\n if let stderrPort = self.hostStdio.stderr {\n let errPipe = Pipe()\n process.stderr = errPipe.fileHandleForWriting\n $0.stderrPipe = errPipe\n\n let type = VsockType(\n port: stderrPort,\n cid: VsockType.hostCID\n )\n let stderrSocket = try Socket(type: type, closeOnDeinit: false)\n try stderrSocket.connect()\n\n let pair = IOPair(\n readFrom: errPipe.fileHandleForReading,\n writeTo: stderrSocket,\n logger: log\n )\n $0.stderr = pair\n\n try pair.relay()\n }\n }\n }\n\n // NOP\n func resize(size: Terminal.Size) throws {}\n\n func closeStdin() throws {\n self.state.withLock {\n if let stdin = $0.stdin {\n stdin.close()\n $0.stdin = nil\n }\n }\n }\n\n func closeAfterExec() throws {\n try self.state.withLock {\n if let stdin = $0.stdinPipe {\n try stdin.fileHandleForReading.close()\n }\n if let stdout = $0.stdoutPipe {\n try stdout.fileHandleForWriting.close()\n }\n if let stderr = $0.stderrPipe {\n try stderr.fileHandleForWriting.close()\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/IndexedAddressAllocator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Collections\nimport Synchronization\n\n/// Maps a network address to an array index value, or nil in the case of a domain error.\npackage typealias AddressToIndexTransform = @Sendable (AddressType) -> Int?\n\n/// Maps an array index value to a network address, or nil in the case of a domain error.\npackage typealias IndexToAddressTransform = @Sendable (Int) -> AddressType?\n\npackage final class IndexedAddressAllocator: AddressAllocator {\n private class State {\n var allocations: BitArray\n var enabled: Bool\n var allocationCount: Int\n let addressToIndex: AddressToIndexTransform\n let indexToAddress: IndexToAddressTransform\n\n init(\n size: Int,\n addressToIndex: @escaping AddressToIndexTransform,\n indexToAddress: @escaping IndexToAddressTransform\n ) {\n self.allocations = BitArray.init(repeating: false, count: size)\n self.enabled = true\n self.allocationCount = 0\n self.addressToIndex = addressToIndex\n self.indexToAddress = indexToAddress\n }\n }\n\n private let stateGuard: Mutex\n\n /// Create an allocator with specified size and index mappings.\n package init(\n size: Int,\n addressToIndex: @escaping AddressToIndexTransform,\n indexToAddress: @escaping IndexToAddressTransform\n ) {\n let state = State(\n size: size,\n addressToIndex: addressToIndex,\n indexToAddress: indexToAddress\n )\n self.stateGuard = Mutex(state)\n }\n\n public func allocate() throws -> AddressType {\n try self.stateGuard.withLock { state in\n guard state.enabled else {\n throw AllocatorError.allocatorDisabled\n }\n\n guard let index = state.allocations.firstIndex(of: false) else {\n throw AllocatorError.allocatorFull\n }\n\n guard let address = state.indexToAddress(index) else {\n throw AllocatorError.invalidIndex(index)\n }\n\n state.allocations[index] = true\n state.allocationCount += 1\n return address\n }\n }\n\n package func reserve(_ address: AddressType) throws {\n try self.stateGuard.withLock { state in\n guard state.enabled else {\n throw AllocatorError.allocatorDisabled\n }\n\n guard let index = state.addressToIndex(address) else {\n throw AllocatorError.invalidAddress(address.description)\n }\n\n guard !state.allocations[index] else {\n throw AllocatorError.alreadyAllocated(\"\\(address.description)\")\n }\n\n state.allocations[index] = true\n state.allocationCount += 1\n }\n\n }\n\n package func release(_ address: AddressType) throws {\n try self.stateGuard.withLock { state in\n guard let index = state.addressToIndex(address) else {\n throw AllocatorError.invalidAddress(address.description)\n }\n\n guard state.allocations[index] else {\n throw AllocatorError.notAllocated(\"\\(address.description)\")\n }\n\n state.allocations[index] = false\n state.allocationCount -= 1\n }\n }\n\n package func disableAllocator() -> Bool {\n self.stateGuard.withLock { state in\n guard state.allocationCount == 0 else {\n return false\n }\n state.enabled = false\n return true\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Types.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// swiftlint:disable large_tuple\n\nimport Foundation\n\nextension EXT4 {\n public struct SuperBlock {\n public var inodesCount: UInt32 = 0\n public var blocksCountLow: UInt32 = 0\n public var rootBlocksCountLow: UInt32 = 0\n public var freeBlocksCountLow: UInt32 = 0\n public var freeInodesCount: UInt32 = 0\n public var firstDataBlock: UInt32 = 0\n public var logBlockSize: UInt32 = 0\n public var logClusterSize: UInt32 = 0\n public var blocksPerGroup: UInt32 = 0\n public var clustersPerGroup: UInt32 = 0\n public var inodesPerGroup: UInt32 = 0\n public var mtime: UInt32 = 0\n public var wtime: UInt32 = 0\n public var mountCount: UInt16 = 0\n public var maxMountCount: UInt16 = 0\n public var magic: UInt16 = 0\n public var state: UInt16 = 0\n public var errors: UInt16 = 0\n public var minorRevisionLevel: UInt16 = 0\n public var lastCheck: UInt32 = 0\n public var checkInterval: UInt32 = 0\n public var creatorOS: UInt32 = 0\n public var revisionLevel: UInt32 = 0\n public var defaultReservedUid: UInt16 = 0\n public var defaultReservedGid: UInt16 = 0\n public var firstInode: UInt32 = 0\n public var inodeSize: UInt16 = 0\n public var blockGroupNr: UInt16 = 0\n public var featureCompat: UInt32 = 0\n public var featureIncompat: UInt32 = 0\n public var featureRoCompat: UInt32 = 0\n public var uuid:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var volumeName:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var lastMounted:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var algorithmUsageBitmap: UInt32 = 0\n public var preallocBlocks: UInt8 = 0\n public var preallocDirBlocks: UInt8 = 0\n public var reservedGdtBlocks: UInt16 = 0\n public var journalUUID:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var journalInum: UInt32 = 0\n public var journalDev: UInt32 = 0\n public var lastOrphan: UInt32 = 0\n public var hashSeed: (UInt32, UInt32, UInt32, UInt32) = (0, 0, 0, 0)\n public var defHashVersion: UInt8 = 0\n public var journalBackupType: UInt8 = 0\n public var descSize: UInt16 = UInt16(MemoryLayout.size)\n public var defaultMountOpts: UInt32 = 0\n public var firstMetaBg: UInt32 = 0\n public var mkfsTime: UInt32 = 0\n public var journalBlocks:\n (\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0\n )\n public var blocksCountHigh: UInt32 = 0\n public var rBlocksCountHigh: UInt32 = 0\n public var freeBlocksCountHigh: UInt32 = 0\n public var minExtraIsize: UInt16 = 0\n public var wantExtraIsize: UInt16 = 0\n public var flags: UInt32 = 0\n public var raidStride: UInt16 = 0\n public var mmpInterval: UInt16 = 0\n public var mmpBlock: UInt64 = 0\n public var raidStripeWidth: UInt32 = 0\n public var logGroupsPerFlex: UInt8 = 0\n public var checksumType: UInt8 = 0\n public var reservedPad: UInt16 = 0\n public var kbytesWritten: UInt64 = 0\n public var snapshotInum: UInt32 = 0\n public var snapshotID: UInt32 = 0\n public var snapshotRBlocksCount: UInt64 = 0\n public var snapshotList: UInt32 = 0\n public var errorCount: UInt32 = 0\n public var firstErrorTime: UInt32 = 0\n public var firstErrorInode: UInt32 = 0\n public var firstErrorBlock: UInt64 = 0\n public var firstErrorFunc:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var firstErrorLine: UInt32 = 0\n public var lastErrorTime: UInt32 = 0\n public var lastErrorInode: UInt32 = 0\n public var lastErrorLine: UInt32 = 0\n public var lastErrorBlock: UInt64 = 0\n public var lastErrorFunc:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var mountOpts:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var userQuotaInum: UInt32 = 0\n public var groupQuotaInum: UInt32 = 0\n public var overheadBlocks: UInt32 = 0\n public var backupBgs: (UInt32, UInt32) = (0, 0)\n public var encryptAlgos: (UInt8, UInt8, UInt8, UInt8) = (0, 0, 0, 0)\n public var encryptPwSalt:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var lpfInode: UInt32 = 0\n public var projectQuotaInum: UInt32 = 0\n public var checksumSeed: UInt32 = 0\n public var wtimeHigh: UInt8 = 0\n public var mtimeHigh: UInt8 = 0\n public var mkfsTimeHigh: UInt8 = 0\n public var lastcheckHigh: UInt8 = 0\n public var firstErrorTimeHigh: UInt8 = 0\n public var lastErrorTimeHigh: UInt8 = 0\n public var pad: (UInt8, UInt8) = (0, 0)\n public var reserved:\n (\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var checksum: UInt32 = 0\n }\n\n struct CompatFeature {\n let rawValue: UInt32\n\n static let dirPrealloc = CompatFeature(rawValue: 0x1)\n static let imagicInodes = CompatFeature(rawValue: 0x2)\n static let hasJournal = CompatFeature(rawValue: 0x4)\n static let extAttr = CompatFeature(rawValue: 0x8)\n static let resizeInode = CompatFeature(rawValue: 0x10)\n static let dirIndex = CompatFeature(rawValue: 0x20)\n static let lazyBg = CompatFeature(rawValue: 0x40)\n static let excludeInode = CompatFeature(rawValue: 0x80)\n static let excludeBitmap = CompatFeature(rawValue: 0x100)\n static let sparseSuper2 = CompatFeature(rawValue: 0x200)\n }\n\n struct IncompatFeature {\n let rawValue: UInt32\n\n static let compression = IncompatFeature(rawValue: 0x1)\n static let filetype = IncompatFeature(rawValue: 0x2)\n static let recover = IncompatFeature(rawValue: 0x4)\n static let journalDev = IncompatFeature(rawValue: 0x8)\n static let metaBg = IncompatFeature(rawValue: 0x10)\n static let extents = IncompatFeature(rawValue: 0x40)\n static let bit64 = IncompatFeature(rawValue: 0x80)\n static let mmp = IncompatFeature(rawValue: 0x100)\n static let flexBg = IncompatFeature(rawValue: 0x200)\n static let eaInode = IncompatFeature(rawValue: 0x400)\n static let dirdata = IncompatFeature(rawValue: 0x1000)\n static let csumSeed = IncompatFeature(rawValue: 0x2000)\n static let largedir = IncompatFeature(rawValue: 0x4000)\n static let inlineData = IncompatFeature(rawValue: 0x8000)\n static let encrypt = IncompatFeature(rawValue: 0x10000)\n }\n\n struct RoCompatFeature {\n let rawValue: UInt32\n\n static let sparseSuper = RoCompatFeature(rawValue: 0x1)\n static let largeFile = RoCompatFeature(rawValue: 0x2)\n static let btreeDir = RoCompatFeature(rawValue: 0x4)\n static let hugeFile = RoCompatFeature(rawValue: 0x8)\n static let gdtCsum = RoCompatFeature(rawValue: 0x10)\n static let dirNlink = RoCompatFeature(rawValue: 0x20)\n static let extraIsize = RoCompatFeature(rawValue: 0x40)\n static let hasSnapshot = RoCompatFeature(rawValue: 0x80)\n static let quota = RoCompatFeature(rawValue: 0x100)\n static let bigalloc = RoCompatFeature(rawValue: 0x200)\n static let metadataCsum = RoCompatFeature(rawValue: 0x400)\n static let replica = RoCompatFeature(rawValue: 0x800)\n static let readonly = RoCompatFeature(rawValue: 0x1000)\n static let project = RoCompatFeature(rawValue: 0x2000)\n }\n\n struct BlockGroupFlag {\n let rawValue: UInt16\n\n static let inodeUninit = BlockGroupFlag(rawValue: 0x1)\n static let blockUninit = BlockGroupFlag(rawValue: 0x2)\n static let inodeZeroed = BlockGroupFlag(rawValue: 0x4)\n }\n\n struct GroupDescriptor {\n let blockBitmapLow: UInt32\n let inodeBitmapLow: UInt32\n let inodeTableLow: UInt32\n let freeBlocksCountLow: UInt16\n let freeInodesCountLow: UInt16\n let usedDirsCountLow: UInt16\n let flags: UInt16\n let excludeBitmapLow: UInt32\n let blockBitmapCsumLow: UInt16\n let inodeBitmapCsumLow: UInt16\n let itableUnusedLow: UInt16\n let checksum: UInt16\n }\n\n struct GroupDescriptor64 {\n let groupDescriptor: GroupDescriptor\n let blockBitmapHigh: UInt32\n let inodeBitmapHigh: UInt32\n let inodeTableHigh: UInt32\n let freeBlocksCountHigh: UInt16\n let freeInodesCountHigh: UInt16\n let usedDirsCountHigh: UInt16\n let itableUnusedHigh: UInt16\n let excludeBitmapHigh: UInt32\n let blockBitmapCsumHigh: UInt16\n let inodeBitmapCsumHigh: UInt16\n let reserved: UInt32\n }\n\n public struct FileModeFlag: Sendable {\n let rawValue: UInt16\n\n public static let S_IXOTH = FileModeFlag(rawValue: 0x1)\n public static let S_IWOTH = FileModeFlag(rawValue: 0x2)\n public static let S_IROTH = FileModeFlag(rawValue: 0x4)\n public static let S_IXGRP = FileModeFlag(rawValue: 0x8)\n public static let S_IWGRP = FileModeFlag(rawValue: 0x10)\n public static let S_IRGRP = FileModeFlag(rawValue: 0x20)\n public static let S_IXUSR = FileModeFlag(rawValue: 0x40)\n public static let S_IWUSR = FileModeFlag(rawValue: 0x80)\n public static let S_IRUSR = FileModeFlag(rawValue: 0x100)\n public static let S_ISVTX = FileModeFlag(rawValue: 0x200)\n public static let S_ISGID = FileModeFlag(rawValue: 0x400)\n public static let S_ISUID = FileModeFlag(rawValue: 0x800)\n public static let S_IFIFO = FileModeFlag(rawValue: 0x1000)\n public static let S_IFCHR = FileModeFlag(rawValue: 0x2000)\n public static let S_IFDIR = FileModeFlag(rawValue: 0x4000)\n public static let S_IFBLK = FileModeFlag(rawValue: 0x6000)\n public static let S_IFREG = FileModeFlag(rawValue: 0x8000)\n public static let S_IFLNK = FileModeFlag(rawValue: 0xA000)\n public static let S_IFSOCK = FileModeFlag(rawValue: 0xC000)\n\n public static let TypeMask = FileModeFlag(rawValue: 0xF000)\n }\n\n typealias InodeNumber = UInt32\n\n public struct Inode {\n var mode: UInt16 = 0\n var uid: UInt16 = 0\n var sizeLow: UInt32 = 0\n var atime: UInt32 = 0\n var ctime: UInt32 = 0\n var mtime: UInt32 = 0\n var dtime: UInt32 = 0\n var gid: UInt16 = 0\n var linksCount: UInt16 = 0\n var blocksLow: UInt32 = 0\n var flags: UInt32 = 0\n var version: UInt32 = 0\n var block:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n )\n var generation: UInt32 = 0\n var xattrBlockLow: UInt32 = 0\n var sizeHigh: UInt32 = 0\n var obsoleteFragmentAddr: UInt32 = 0\n var blocksHigh: UInt16 = 0\n var xattrBlockHigh: UInt16 = 0\n var uidHigh: UInt16 = 0\n var gidHigh: UInt16 = 0\n var checksumLow: UInt16 = 0\n var reserved: UInt16 = 0\n var extraIsize: UInt16 = 0\n var checksumHigh: UInt16 = 0\n var ctimeExtra: UInt32 = 0\n var mtimeExtra: UInt32 = 0\n var atimeExtra: UInt32 = 0\n var crtime: UInt32 = 0\n var crtimeExtra: UInt32 = 0\n var versionHigh: UInt32 = 0\n var projid: UInt32 = 0 // Size until this point is 160 bytes\n var inlineXattrs:\n ( // 96 bytes for extended attributes\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0\n )\n\n public static func Mode(_ mode: FileModeFlag, _ perm: UInt16) -> UInt16 {\n mode.rawValue | perm\n }\n }\n\n struct InodeFlag {\n let rawValue: UInt32\n\n static let secRm = InodeFlag(rawValue: 0x1)\n static let unRm = InodeFlag(rawValue: 0x2)\n static let compressed = InodeFlag(rawValue: 0x4)\n static let sync = InodeFlag(rawValue: 0x8)\n static let immutable = InodeFlag(rawValue: 0x10)\n static let append = InodeFlag(rawValue: 0x20)\n static let noDump = InodeFlag(rawValue: 0x40)\n static let noAtime = InodeFlag(rawValue: 0x80)\n static let dirtyCompressed = InodeFlag(rawValue: 0x100)\n static let compressedClusters = InodeFlag(rawValue: 0x200)\n static let noCompress = InodeFlag(rawValue: 0x400)\n static let encrypted = InodeFlag(rawValue: 0x800)\n static let hashedIndex = InodeFlag(rawValue: 0x1000)\n static let magic = InodeFlag(rawValue: 0x2000)\n static let journalData = InodeFlag(rawValue: 0x4000)\n static let noTail = InodeFlag(rawValue: 0x8000)\n static let dirSync = InodeFlag(rawValue: 0x10000)\n static let topDir = InodeFlag(rawValue: 0x20000)\n static let hugeFile = InodeFlag(rawValue: 0x40000)\n static let extents = InodeFlag(rawValue: 0x80000)\n static let eaInode = InodeFlag(rawValue: 0x200000)\n static let eofBlocks = InodeFlag(rawValue: 0x400000)\n static let snapfile = InodeFlag(rawValue: 0x0100_0000)\n static let snapfileDeleted = InodeFlag(rawValue: 0x0400_0000)\n static let snapfileShrunk = InodeFlag(rawValue: 0x0800_0000)\n static let inlineData = InodeFlag(rawValue: 0x1000_0000)\n static let projectIDInherit = InodeFlag(rawValue: 0x2000_0000)\n static let reserved = InodeFlag(rawValue: 0x8000_0000)\n }\n\n struct ExtentHeader {\n let magic: UInt16\n let entries: UInt16\n let max: UInt16\n let depth: UInt16\n let generation: UInt32\n }\n\n struct ExtentIndex {\n let block: UInt32\n let leafLow: UInt32\n let leafHigh: UInt16\n let unused: UInt16\n }\n\n struct ExtentLeaf {\n let block: UInt32\n let length: UInt16\n let startHigh: UInt16\n let startLow: UInt32\n }\n\n struct ExtentTail {\n let checksum: UInt32\n }\n\n struct ExtentIndexNode {\n var header: ExtentHeader\n var indices: [ExtentIndex]\n }\n\n struct ExtentLeafNode {\n var header: ExtentHeader\n var leaves: [ExtentLeaf]\n }\n\n struct DirectoryEntry {\n let inode: InodeNumber\n let recordLength: UInt16\n let nameLength: UInt8\n let fileType: UInt8\n // let name: [UInt8]\n }\n\n enum FileType: UInt8 {\n case unknown = 0x0\n case regular = 0x1\n case directory = 0x2\n case character = 0x3\n case block = 0x4\n case fifo = 0x5\n case socket = 0x6\n case symbolicLink = 0x7\n }\n\n struct DirectoryEntryTail {\n let reservedZero1: UInt32\n let recordLength: UInt16\n let reservedZero2: UInt8\n let fileType: UInt8\n let checksum: UInt32\n }\n\n struct DirectoryTreeRoot {\n let dot: DirectoryEntry\n let dotName: [UInt8]\n let dotDot: DirectoryEntry\n let dotDotName: [UInt8]\n let reservedZero: UInt32\n let hashVersion: UInt8\n let infoLength: UInt8\n let indirectLevels: UInt8\n let unusedFlags: UInt8\n let limit: UInt16\n let count: UInt16\n let block: UInt32\n // let entries: [DirectoryTreeEntry]\n }\n\n struct DirectoryTreeNode {\n let fakeInode: UInt32\n let fakeRecordLength: UInt16\n let nameLength: UInt8\n let fileType: UInt8\n let limit: UInt16\n let count: UInt16\n let block: UInt32\n // let entries: [DirectoryTreeEntry]\n }\n\n struct DirectoryTreeEntry {\n let hash: UInt32\n let block: UInt32\n }\n\n struct DirectoryTreeTail {\n let reserved: UInt32\n let checksum: UInt32\n }\n\n struct XAttrEntry {\n let nameLength: UInt8\n let nameIndex: UInt8\n let valueOffset: UInt16\n let valueInum: UInt32\n let valueSize: UInt32\n let hash: UInt32\n }\n\n struct XAttrHeader {\n let magic: UInt32\n let referenceCount: UInt32\n let blocks: UInt32\n let hash: UInt32\n let checksum: UInt32\n let reserved: [UInt32]\n }\n\n}\n\nextension EXT4.Inode {\n public static func Root() -> EXT4.Inode {\n var inode = Self() // inode\n inode.mode = Self.Mode(.S_IFDIR, 0o755)\n inode.linksCount = 2\n inode.uid = 0\n inode.gid = 0\n // time\n let now = Date().fs()\n let now_lo: UInt32 = now.lo\n let now_hi: UInt32 = now.hi\n inode.atime = now_lo\n inode.atimeExtra = now_hi\n inode.ctime = now_lo\n inode.ctimeExtra = now_hi\n inode.mtime = now_lo\n inode.mtimeExtra = now_hi\n inode.crtime = now_lo\n inode.crtimeExtra = now_hi\n inode.flags = EXT4.InodeFlag.hugeFile.rawValue\n inode.extraIsize = UInt16(EXT4.ExtraIsize)\n return inode\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/UnsafeLittleEndianBytes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n// takes a pointer and converts its contents to native endian bytes\npublic func withUnsafeLittleEndianBytes(of value: T, body: (UnsafeRawBufferPointer) throws -> Result)\n rethrows -> Result\n{\n switch Endian {\n case .little:\n return try withUnsafeBytes(of: value) { bytes in\n try body(bytes)\n }\n case .big:\n return try withUnsafeBytes(of: value) { buffer in\n let reversedBuffer = Array(buffer.reversed())\n return try reversedBuffer.withUnsafeBytes { buf in\n try body(buf)\n }\n }\n }\n}\n\npublic func withUnsafeLittleEndianBuffer(\n of value: UnsafeRawBufferPointer, body: (UnsafeRawBufferPointer) throws -> T\n) rethrows -> T {\n switch Endian {\n case .little:\n return try body(value)\n case .big:\n let reversed = Array(value.reversed())\n return try reversed.withUnsafeBytes { buf in\n try body(buf)\n }\n }\n}\n\nextension UnsafeRawBufferPointer {\n // loads littleEndian raw data, converts it native endian format and calls UnsafeRawBufferPointer.load\n public func loadLittleEndian(as type: T.Type) -> T {\n switch Endian {\n case .little:\n return self.load(as: T.self)\n case .big:\n let buffer = Array(self.reversed())\n return buffer.withUnsafeBytes { ptr in\n ptr.load(as: T.self)\n }\n }\n }\n}\n\npublic enum Endianness {\n case little\n case big\n}\n\n// returns current endianness\npublic var Endian: Endianness {\n switch CFByteOrderGetCurrent() {\n case CFByteOrder(CFByteOrderLittleEndian.rawValue):\n return .little\n case CFByteOrder(CFByteOrderBigEndian.rawValue):\n return .big\n default:\n fatalError(\"impossible\")\n }\n}\n"], ["/containerization/Sources/ContainerizationError/ContainerizationError.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// The core error type for Containerization.\n///\n/// Most API surfaces for the core container/process/agent types will\n/// return a ContainerizationError.\npublic struct ContainerizationError: Swift.Error, Sendable {\n /// A code describing the error encountered.\n public var code: Code\n /// A description of the error.\n public var message: String\n /// The original error which led to this error being thrown.\n public var cause: (any Error)?\n\n /// Creates a new error.\n ///\n /// - Parameters:\n /// - code: The error code.\n /// - message: A description of the error.\n /// - cause: The original error which led to this error being thrown.\n public init(_ code: Code, message: String, cause: (any Error)? = nil) {\n self.code = code\n self.message = message\n self.cause = cause\n }\n\n /// Creates a new error.\n ///\n /// - Parameters:\n /// - rawCode: The error code value as a String.\n /// - message: A description of the error.\n /// - cause: The original error which led to this error being thrown.\n public init(_ rawCode: String, message: String, cause: (any Error)? = nil) {\n self.code = Code(rawValue: rawCode)\n self.message = message\n self.cause = cause\n }\n\n /// Provides a unique hash of the error.\n public func hash(into hasher: inout Hasher) {\n hasher.combine(self.code)\n hasher.combine(self.message)\n }\n\n /// Equality operator for the error. Uses the code and message.\n public static func == (lhs: Self, rhs: Self) -> Bool {\n lhs.code == rhs.code && lhs.message == rhs.message\n }\n\n /// Checks if the given error has the provided code.\n public func isCode(_ code: Code) -> Bool {\n self.code == code\n }\n}\n\nextension ContainerizationError: CustomStringConvertible {\n /// Description of the error.\n public var description: String {\n guard let cause = self.cause else {\n return \"\\(self.code): \\\"\\(self.message)\\\"\"\n }\n return \"\\(self.code): \\\"\\(self.message)\\\" (cause: \\\"\\(cause)\\\")\"\n }\n}\n\nextension ContainerizationError {\n /// Codes for a `ContainerizationError`.\n public struct Code: Sendable, Hashable {\n private enum Value: Hashable, Sendable, CaseIterable {\n case unknown\n case invalidArgument\n case internalError\n case exists\n case notFound\n case cancelled\n case invalidState\n case empty\n case timeout\n case unsupported\n case interrupted\n }\n\n private var value: Value\n private init(_ value: Value) {\n self.value = value\n }\n\n init(rawValue: String) {\n let values = Value.allCases.reduce(into: [String: Value]()) {\n $0[String(describing: $1)] = $1\n }\n\n let match = values[rawValue]\n guard let match else {\n fatalError(\"invalid Code Value \\(rawValue)\")\n }\n self.value = match\n }\n\n public static var unknown: Self {\n Self(.unknown)\n }\n\n public static var invalidArgument: Self {\n Self(.invalidArgument)\n }\n\n public static var internalError: Self {\n Self(.internalError)\n }\n\n public static var exists: Self {\n Self(.exists)\n }\n\n public static var notFound: Self {\n Self(.notFound)\n }\n\n public static var cancelled: Self {\n Self(.cancelled)\n }\n\n public static var invalidState: Self {\n Self(.invalidState)\n }\n\n public static var empty: Self {\n Self(.empty)\n }\n\n public static var timeout: Self {\n Self(.timeout)\n }\n\n public static var unsupported: Self {\n Self(.unsupported)\n }\n\n public static var interrupted: Self {\n Self(.interrupted)\n }\n }\n}\n\nextension ContainerizationError.Code: CustomStringConvertible {\n public var description: String {\n String(describing: self.value)\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/AsyncLock.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// `AsyncLock` provides a familiar locking API, with the main benefit being that it\n/// is safe to call async methods while holding the lock. This is primarily used in spots\n/// where an actor makes sense, but we may need to ensure we don't fall victim to actor\n/// reentrancy issues.\npublic actor AsyncLock {\n private var busy = false\n private var queue: ArraySlice> = []\n\n public struct Context: Sendable {\n fileprivate init() {}\n }\n\n public init() {}\n\n /// withLock provides a scoped locking API to run a function while holding the lock.\n public func withLock(_ body: @Sendable @escaping (Context) async throws -> T) async rethrows -> T {\n while self.busy {\n await withCheckedContinuation { cc in\n self.queue.append(cc)\n }\n }\n\n self.busy = true\n\n defer {\n self.busy = false\n if let next = self.queue.popFirst() {\n next.resume(returning: ())\n } else {\n self.queue = []\n }\n }\n\n let context = Context()\n return try await body(context)\n }\n}\n"], ["/containerization/Sources/ContainerizationNetlink/Types.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport Foundation\n\nstruct SocketType {\n static let SOCK_RAW: Int32 = 3\n}\n\nstruct AddressFamily {\n static let AF_UNSPEC: UInt16 = 0\n static let AF_INET: UInt16 = 2\n static let AF_INET6: UInt16 = 10\n static let AF_NETLINK: UInt16 = 16\n static let AF_PACKET: UInt16 = 17\n}\n\nstruct NetlinkProtocol {\n static let NETLINK_ROUTE: Int32 = 0\n}\n\nstruct NetlinkType {\n static let NLMSG_NOOP: UInt16 = 1\n static let NLMSG_ERROR: UInt16 = 2\n static let NLMSG_DONE: UInt16 = 3\n static let NLMSG_OVERRUN: UInt16 = 4\n static let RTM_NEWLINK: UInt16 = 16\n static let RTM_DELLINK: UInt16 = 17\n static let RTM_GETLINK: UInt16 = 18\n static let RTM_NEWADDR: UInt16 = 20\n static let RTM_NEWROUTE: UInt16 = 24\n}\n\nstruct NetlinkFlags {\n static let NLM_F_REQUEST: UInt16 = 0x01\n static let NLM_F_MULTI: UInt16 = 0x02\n static let NLM_F_ACK: UInt16 = 0x04\n static let NLM_F_ECHO: UInt16 = 0x08\n static let NLM_F_DUMP_INTR: UInt16 = 0x10\n static let NLM_F_DUMP_FILTERED: UInt16 = 0x20\n\n // GET request\n static let NLM_F_ROOT: UInt16 = 0x100\n static let NLM_F_MATCH: UInt16 = 0x200\n static let NLM_F_ATOMIC: UInt16 = 0x400\n static let NLM_F_DUMP: UInt16 = NetlinkFlags.NLM_F_ROOT | NetlinkFlags.NLM_F_MATCH\n\n // NEW request flags\n static let NLM_F_REPLACE: UInt16 = 0x100\n static let NLM_F_EXCL: UInt16 = 0x200\n static let NLM_F_CREATE: UInt16 = 0x400\n static let NLM_F_APPEND: UInt16 = 0x800\n}\n\nstruct NetlinkScope {\n static let RT_SCOPE_UNIVERSE: UInt8 = 0\n}\n\nstruct InterfaceFlags {\n static let IFF_UP: UInt32 = 1 << 0\n static let DEFAULT_CHANGE: UInt32 = 0xffff_ffff\n}\n\nstruct LinkAttributeType {\n static let IFLA_EXT_IFNAME: UInt16 = 3\n static let IFLA_MTU: UInt16 = 4\n static let IFLA_EXT_MASK: UInt16 = 29\n}\n\nstruct LinkAttributeMaskFilter {\n static let RTEXT_FILTER_VF: UInt32 = 1 << 0\n static let RTEXT_FILTER_SKIP_STATS: UInt32 = 1 << 3\n}\n\nstruct AddressAttributeType {\n // subnet mask\n static let IFA_ADDRESS: UInt16 = 1\n // IPv4 address\n static let IFA_LOCAL: UInt16 = 2\n}\n\nstruct RouteTable {\n static let MAIN: UInt8 = 254\n}\n\nstruct RouteProtocol {\n static let UNSPEC: UInt8 = 0\n static let REDIRECT: UInt8 = 1\n static let KERNEL: UInt8 = 2\n static let BOOT: UInt8 = 3\n static let STATIC: UInt8 = 4\n}\n\nstruct RouteScope {\n static let UNIVERSE: UInt8 = 0\n static let LINK: UInt8 = 253\n}\n\nstruct RouteType {\n static let UNSPEC: UInt8 = 0\n static let UNICAST: UInt8 = 1\n}\n\nstruct RouteAttributeType {\n static let UNSPEC: UInt16 = 0\n static let DST: UInt16 = 1\n static let SRC: UInt16 = 2\n static let IIF: UInt16 = 3\n static let OIF: UInt16 = 4\n static let GATEWAY: UInt16 = 5\n static let PRIORITY: UInt16 = 6\n static let PREFSRC: UInt16 = 7\n}\n\nprotocol Bindable: Equatable {\n static var size: Int { get }\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int\n}\n\nstruct SockaddrNetlink: Bindable {\n static let size = 12\n\n var family: UInt16\n var pad: UInt16 = 0\n var pid: UInt32\n var groups: UInt32\n\n init(family: UInt16 = 0, pid: UInt32 = 0, groups: UInt32 = 0) {\n self.family = family\n self.pid = pid\n self.groups = groups\n }\n\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let offset = buffer.copyIn(as: UInt16.self, value: family, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: pid, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: groups, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n family = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n pid = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n groups = value\n\n return offset + Self.size\n }\n}\n\nstruct NetlinkMessageHeader: Bindable {\n static let size = 16\n\n var len: UInt32\n var type: UInt16\n var flags: UInt16\n var seq: UInt32\n var pid: UInt32\n\n init(len: UInt32 = 0, type: UInt16 = 0, flags: UInt16 = 0, seq: UInt32? = nil, pid: UInt32 = 0) {\n self.len = len\n self.type = type\n self.flags = flags\n self.seq = seq ?? UInt32.random(in: 0.. Int {\n guard let offset = buffer.copyIn(as: UInt32.self, value: len, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt16.self, value: type, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt16.self, value: flags, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: seq, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: pid, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n len = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n type = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n flags = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n seq = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n pid = value\n\n return offset\n }\n\n var moreResponses: Bool {\n (self.flags & NetlinkFlags.NLM_F_MULTI) != 0\n && (self.type != NetlinkType.NLMSG_DONE && self.type != NetlinkType.NLMSG_ERROR\n && self.type != NetlinkType.NLMSG_OVERRUN)\n }\n}\n\nstruct InterfaceInfo: Bindable {\n static let size = 16\n\n var family: UInt8\n var _pad: UInt8 = 0\n var type: UInt16\n var index: Int32\n var flags: UInt32\n var change: UInt32\n\n init(\n family: UInt8 = UInt8(AddressFamily.AF_UNSPEC), type: UInt16 = 0, index: Int32 = 0, flags: UInt32 = 0,\n change: UInt32 = 0\n ) {\n self.family = family\n self.type = type\n self.index = index\n self.flags = flags\n self.change = change\n }\n\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let offset = buffer.copyIn(as: UInt8.self, value: family, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: _pad, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt16.self, value: type, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: Int32.self, value: index, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: flags, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: change, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n family = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n _pad = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n type = value\n\n guard let (offset, value) = buffer.copyOut(as: Int32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n index = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n flags = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n change = value\n\n return offset\n }\n}\n\nstruct AddressInfo: Bindable {\n static let size = 8\n\n var family: UInt8\n var prefixLength: UInt8\n var flags: UInt8\n var scope: UInt8\n var index: UInt32\n\n init(\n family: UInt8 = UInt8(AddressFamily.AF_UNSPEC), prefixLength: UInt8 = 32, flags: UInt8 = 0, scope: UInt8 = 0,\n index: UInt32 = 0\n ) {\n self.family = family\n self.prefixLength = prefixLength\n self.flags = flags\n self.scope = scope\n self.index = index\n }\n\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let offset = buffer.copyIn(as: UInt8.self, value: family, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: prefixLength, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: flags, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: scope, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: index, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n family = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n prefixLength = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n flags = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n scope = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n index = value\n\n return offset\n }\n}\n\nstruct RouteInfo: Bindable {\n static let size = 12\n\n var family: UInt8\n var dstLen: UInt8\n var srcLen: UInt8\n var tos: UInt8\n var table: UInt8\n var proto: UInt8\n var scope: UInt8\n var type: UInt8\n var flags: UInt32\n\n init(\n family: UInt8 = UInt8(AddressFamily.AF_INET),\n dstLen: UInt8,\n srcLen: UInt8,\n tos: UInt8,\n table: UInt8,\n proto: UInt8,\n scope: UInt8,\n type: UInt8,\n flags: UInt32\n ) {\n self.family = family\n self.dstLen = dstLen\n self.srcLen = srcLen\n self.tos = tos\n self.table = table\n self.proto = proto\n self.scope = scope\n self.type = type\n self.flags = flags\n }\n\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let offset = buffer.copyIn(as: UInt8.self, value: family, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: dstLen, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: srcLen, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: tos, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: table, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: proto, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: scope, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: type, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: flags, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n family = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n dstLen = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n srcLen = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n tos = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n table = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n proto = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n scope = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n type = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n flags = value\n\n return offset\n }\n}\n\n/// A route information.\npublic struct RTAttribute: Bindable {\n static let size = 4\n\n public var len: UInt16\n public var type: UInt16\n public var paddedLen: Int { Int(((len + 3) >> 2) << 2) }\n\n init(len: UInt16 = 0, type: UInt16 = 0) {\n self.len = len\n self.type = type\n }\n\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let offset = buffer.copyIn(as: UInt16.self, value: len, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt16.self, value: type, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n len = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n type = value\n\n return offset\n }\n}\n\n/// A route information with data.\npublic struct RTAttributeData {\n public let attribute: RTAttribute\n public let data: [UInt8]\n}\n\n/// A response from the get link command.\npublic struct LinkResponse {\n public let interfaceIndex: Int32\n public let attrDatas: [RTAttributeData]\n}\n\n/// Errors thrown when parsing netlink data.\npublic enum NetlinkDataError: Swift.Error, CustomStringConvertible, Equatable {\n case sendMarshalFailure\n case recvUnmarshalFailure\n case responseError(rc: Int32)\n case unsupportedPlatform\n\n /// The description of the errors.\n public var description: String {\n switch self {\n case .sendMarshalFailure:\n return \"could not marshal netlink packet\"\n case .recvUnmarshalFailure:\n return \"could not unmarshal netlink packet\"\n case .responseError(let rc):\n return \"netlink response indicates error, rc = \\(rc)\"\n case .unsupportedPlatform:\n return \"unsupported platform\"\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/LocalContent.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Crypto\nimport Foundation\n\npublic final class LocalContent: Content {\n public let path: URL\n private let file: FileHandle\n\n public init(path: URL) throws {\n guard FileManager.default.fileExists(atPath: path.path) else {\n throw ContainerizationError(.notFound, message: \"Content at path \\(path.absolutePath())\")\n }\n\n self.file = try FileHandle(forReadingFrom: path)\n self.path = path\n }\n\n public func digest() throws -> SHA256.Digest {\n let bufferSize = 64 * 1024 // 64 KB\n var hasher = SHA256()\n\n try self.file.seek(toOffset: 0)\n while case let data = file.readData(ofLength: bufferSize), !data.isEmpty {\n hasher.update(data: data)\n }\n\n let digest = hasher.finalize()\n\n try self.file.seek(toOffset: 0)\n return digest\n }\n\n public func data(offset: UInt64 = 0, length size: Int = 0) throws -> Data? {\n try file.seek(toOffset: offset)\n if size == 0 {\n return try file.readToEnd()\n }\n return try file.read(upToCount: size)\n }\n\n public func data() throws -> Data {\n try Data(contentsOf: self.path)\n }\n\n public func size() throws -> UInt64 {\n let fileAttrs = try FileManager.default.attributesOfItem(atPath: self.path.absolutePath())\n if let size = fileAttrs[FileAttributeKey.size] as? UInt64 {\n return size\n }\n throw ContainerizationError(.internalError, message: \"Could not determine file size for \\(path.absolutePath())\")\n }\n\n public func decode() throws -> T where T: Decodable {\n let json = JSONDecoder()\n let data = try Data(contentsOf: self.path)\n return try json.decode(T.self, from: data)\n }\n\n deinit {\n try? self.file.close()\n }\n}\n"], ["/containerization/Sources/Containerization/Agent/Vminitd+SocketRelay.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension Vminitd: SocketRelayAgent {\n /// Sets up a relay between a host socket to a newly created guest socket, or vice versa.\n public func relaySocket(port: UInt32, configuration: UnixSocketConfiguration) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest.with {\n $0.id = configuration.id\n $0.vsockPort = port\n\n if let perms = configuration.permissions {\n $0.guestSocketPermissions = UInt32(perms.rawValue)\n }\n\n switch configuration.direction {\n case .into:\n $0.guestPath = configuration.destination.path\n $0.action = .into\n case .outOf:\n $0.guestPath = configuration.source.path\n $0.action = .outOf\n }\n }\n _ = try await client.proxyVsock(request)\n }\n\n /// Stops the specified socket relay.\n public func stopSocketRelay(configuration: UnixSocketConfiguration) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest.with {\n $0.id = configuration.id\n }\n _ = try await client.stopVsockProxy(request)\n }\n}\n"], ["/containerization/Sources/Containerization/UnixSocketConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\n/// Represents a UnixSocket that can be shared into or out of a container/guest.\npublic struct UnixSocketConfiguration: Sendable {\n // TODO: Realistically, we can just hash this struct and use it as the \"id\".\n package var id: String {\n _id\n }\n\n private let _id = UUID().uuidString\n\n /// The path to the socket you'd like relayed. For .into\n /// direction this should be the path on the host to a unix socket.\n /// For direction .outOf this should be the path in the container/guest\n /// to a unix socket.\n public var source: URL\n\n /// The path you'd like the socket to be relayed to. For .into\n /// direction this should be the path in the container/guest. For\n /// direction .outOf this should be the path on your host.\n public var destination: URL\n\n /// What to set the file permissions of the unix socket being created\n /// to. For .into direction this will be the socket in the guest. For\n /// .outOf direction this will be the socket on the host.\n public var permissions: FilePermissions?\n\n /// The direction of the relay. `.into` for sharing a unix socket on your\n /// host into the container/guest. `outOf` shares a socket in the container/guest\n /// onto your host.\n public var direction: Direction\n\n /// Type that denotes the direction of the unix socket relay.\n public enum Direction: Sendable {\n /// Share the socket into the container/guest.\n case into\n /// Share a socket in the container/guest onto the host.\n case outOf\n }\n\n public init(\n source: URL,\n destination: URL,\n permissions: FilePermissions? = nil,\n direction: Direction = .into\n ) {\n self.source = source\n self.destination = destination\n self.permissions = permissions\n self.direction = direction\n }\n}\n"], ["/containerization/Sources/SendablePropertyMacros/SendablePropertyMacroUnchecked.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SwiftCompilerPlugin\nimport SwiftParser\nimport SwiftSyntax\nimport SwiftSyntaxBuilder\nimport SwiftSyntaxMacros\n\n/// A macro that allows to make a property of a custom type thread-safe keeping the `Sendable` conformance of the type. This macro can be used with classes and enums. Avoid using it with structs, arrays, and dictionaries.\npublic struct SendablePropertyMacroUnchecked: PeerMacro {\n private static func peerPropertyName(for propertyName: String) -> String {\n \"_\" + propertyName\n }\n\n /// The macro expansion that introduces a `Sendable`-conforming \"peer\" declaration for a thread-safe storage for the value of the given declaration of a variable.\n /// - Parameters:\n /// - node: The given attribute node.\n /// - declaration: The given declaration.\n /// - context: The macro expansion context.\n public static func expansion(\n of node: SwiftSyntax.AttributeSyntax, providingPeersOf declaration: some SwiftSyntax.DeclSyntaxProtocol, in context: some SwiftSyntaxMacros.MacroExpansionContext\n ) throws -> [SwiftSyntax.DeclSyntax] {\n guard let varDecl = declaration.as(VariableDeclSyntax.self),\n let binding = varDecl.bindings.first,\n let pattern = binding.pattern.as(IdentifierPatternSyntax.self)\n else {\n throw SendablePropertyError.onlyApplicableToVar\n }\n\n let propertyName = pattern.identifier.text\n let hasInitializer = binding.initializer != nil\n let initializerValue = binding.initializer?.value.description ?? \"nil\"\n\n var genericTypeAnnotation = \"\"\n if let typeAnnotation = binding.typeAnnotation {\n let typeName = typeAnnotation.type.description.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)\n genericTypeAnnotation = \"<\\(typeName)\\(hasInitializer ? \"\" : \"?\")>\"\n }\n\n let accessLevel = varDecl.modifiers.first(where: { [\"open\", \"public\", \"internal\", \"fileprivate\", \"private\"].contains($0.name.text) })?.name.text ?? \"internal\"\n\n // Create a peer property\n let peerPropertyName = self.peerPropertyName(for: propertyName)\n let peerProperty: DeclSyntax =\n \"\"\"\n \\(raw: accessLevel) let \\(raw: peerPropertyName) = Synchronized\\(raw: genericTypeAnnotation)(\\(raw: initializerValue))\n \"\"\"\n return [peerProperty]\n }\n}\n\nextension SendablePropertyMacroUnchecked: AccessorMacro {\n /// The macro expansion that adds `Sendable`-conforming accessors to the given declaration of a variable.\n /// - Parameters:\n /// - node: The given attribute node.\n /// - declaration: The given declaration.\n /// - context: The macro expansion context.\n public static func expansion(\n of node: SwiftSyntax.AttributeSyntax, providingAccessorsOf declaration: some SwiftSyntax.DeclSyntaxProtocol, in context: some SwiftSyntaxMacros.MacroExpansionContext\n ) throws -> [SwiftSyntax.AccessorDeclSyntax] {\n guard let varDecl = declaration.as(VariableDeclSyntax.self),\n let binding = varDecl.bindings.first,\n let pattern = binding.pattern.as(IdentifierPatternSyntax.self)\n else {\n throw SendablePropertyError.onlyApplicableToVar\n }\n\n let propertyName = pattern.identifier.text\n let hasInitializer = binding.initializer != nil\n\n // Replace the property with an accessor\n let peerPropertyName = Self.peerPropertyName(for: propertyName)\n\n let accessorGetter: AccessorDeclSyntax =\n \"\"\"\n get {\n \\(raw: peerPropertyName).withLock { $0\\(raw: hasInitializer ? \"\" : \"!\") }\n }\n \"\"\"\n let accessorSetter: AccessorDeclSyntax =\n \"\"\"\n set {\n \\(raw: peerPropertyName).withLock { $0 = newValue }\n }\n \"\"\"\n\n return [accessorGetter, accessorSetter]\n }\n}\n"], ["/containerization/Sources/SendablePropertyMacros/SendablePropertyMacro.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SwiftCompilerPlugin\nimport SwiftParser\nimport SwiftSyntax\nimport SwiftSyntaxBuilder\nimport SwiftSyntaxMacros\n\n/// A macro that allows to make a property of a supported type thread-safe keeping the `Sendable` conformance of the type.\npublic struct SendablePropertyMacro: PeerMacro {\n private static let allowedTypes: Set = [\n \"Int\", \"UInt\", \"Int16\", \"UInt16\", \"Int32\", \"UInt32\", \"Int64\", \"UInt64\", \"Float\", \"Double\", \"Bool\", \"UnsafeRawPointer\", \"UnsafeMutableRawPointer\", \"UnsafePointer\",\n \"UnsafeMutablePointer\",\n ]\n\n private static func checkPropertyType(in declaration: some DeclSyntaxProtocol) throws {\n guard let varDecl = declaration.as(VariableDeclSyntax.self),\n let binding = varDecl.bindings.first,\n let typeAnnotation = binding.typeAnnotation,\n let id = typeAnnotation.type.as(IdentifierTypeSyntax.self)\n else {\n // Nothing to check.\n return\n }\n\n var typeName = id.name.text\n // Allow optionals of the allowed types.\n if typeName.prefix(9) == \"Optional<\" && typeName.suffix(1) == \">\" {\n typeName = String(typeName.dropFirst(9).dropLast(1))\n }\n // Allow generics of the allowed types.\n if typeName.contains(\"<\") {\n typeName = String(typeName.prefix { $0 != \"<\" })\n }\n\n guard allowedTypes.contains(typeName) else {\n throw SendablePropertyError.notApplicableToType\n }\n }\n\n /// The macro expansion that introduces a `Sendable`-conforming \"peer\" declaration for a thread-safe storage for the value of the given declaration of a variable.\n /// - Parameters:\n /// - node: The given attribute node.\n /// - declaration: The given declaration.\n /// - context: The macro expansion context.\n public static func expansion(\n of node: SwiftSyntax.AttributeSyntax, providingPeersOf declaration: some SwiftSyntax.DeclSyntaxProtocol, in context: some SwiftSyntaxMacros.MacroExpansionContext\n ) throws -> [SwiftSyntax.DeclSyntax] {\n try checkPropertyType(in: declaration)\n return try SendablePropertyMacroUnchecked.expansion(of: node, providingPeersOf: declaration, in: context)\n }\n}\n\nextension SendablePropertyMacro: AccessorMacro {\n /// The macro expansion that adds `Sendable`-conforming accessors to the given declaration of a variable.\n /// - Parameters:\n /// - node: The given attribute node.\n /// - declaration: The given declaration.\n /// - context: The macro expansion context.\n public static func expansion(\n of node: SwiftSyntax.AttributeSyntax, providingAccessorsOf declaration: some SwiftSyntax.DeclSyntaxProtocol, in context: some SwiftSyntaxMacros.MacroExpansionContext\n ) throws -> [SwiftSyntax.AccessorDeclSyntax] {\n try checkPropertyType(in: declaration)\n return try SendablePropertyMacroUnchecked.expansion(of: node, providingAccessorsOf: declaration, in: context)\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/FileArchiveWriterDelegate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\ninternal final class FileArchiveWriterDelegate {\n public let path: FilePath\n private var fd: FileDescriptor!\n\n public init(path: FilePath) {\n self.path = path\n }\n\n public convenience init(url: URL) {\n self.init(path: FilePath(url.path))\n }\n\n public func open(archive: ArchiveWriter) throws {\n self.fd = try FileDescriptor.open(\n self.path, .writeOnly, options: [.create, .append], permissions: [.groupRead, .otherRead, .ownerReadWrite])\n }\n\n public func write(archive: ArchiveWriter, buffer: UnsafeRawBufferPointer) throws -> Int {\n try fd.write(buffer)\n }\n\n public func close(archive: ArchiveWriter) throws {\n try self.fd.close()\n }\n\n public func free(archive: ArchiveWriter) {\n self.fd = nil\n }\n\n deinit {\n if let fd = self.fd {\n try? fd.close()\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/NetworkAddress.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Errors related to IP and CIDR addresses.\npublic enum NetworkAddressError: Swift.Error, Equatable, CustomStringConvertible {\n case invalidStringAddress(address: String)\n case invalidNetworkByteAddress(address: [UInt8])\n case invalidCIDR(cidr: String)\n case invalidAddressForSubnet(address: String, cidr: String)\n case invalidAddressRange(lower: String, upper: String)\n\n public var description: String {\n switch self {\n case .invalidStringAddress(let address):\n return \"invalid IP address string \\(address)\"\n case .invalidNetworkByteAddress(let address):\n return \"invalid IP address bytes \\(address)\"\n case .invalidCIDR(let cidr):\n return \"invalid CIDR block: \\(cidr)\"\n case .invalidAddressForSubnet(let address, let cidr):\n return \"invalid address \\(address) for subnet \\(cidr)\"\n case .invalidAddressRange(let lower, let upper):\n return \"invalid range for addresses \\(lower) and \\(upper)\"\n }\n }\n}\n\npublic typealias PrefixLength = UInt8\n\nextension PrefixLength {\n /// Compute a bit mask that passes the suffix bits, given the network prefix mask length.\n public var suffixMask32: UInt32 {\n if self <= 0 {\n return 0xffff_ffff\n }\n return self >= 32 ? 0x0000_0000 : (1 << (32 - self)) - 1\n }\n\n /// Compute a bit mask that passes the prefix bits, given the network prefix mask length.\n public var prefixMask32: UInt32 {\n ~self.suffixMask32\n }\n\n /// Compute a bit mask that passes the suffix bits, given the network prefix mask length.\n public var suffixMask48: UInt64 {\n if self <= 0 {\n return 0x0000_ffff_ffff_ffff\n }\n return self >= 48 ? 0x0000_0000_0000_0000 : (1 << (48 - self)) - 1\n }\n\n /// Compute a bit mask that passes the prefix bits, given the network prefix mask length.\n public var prefixMask48: UInt64 {\n ~self.suffixMask48 & 0x0000_ffff_ffff_ffff\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/ContentStoreProtocol.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Crypto\nimport Foundation\n\n/// Protocol for defining a content store where OCI image metadata and layers will be managed\n/// and manipulated.\npublic protocol ContentStore: Sendable {\n /// Retrieves a piece of Content based on the digest string.\n /// Returns `nil` if the requested digest is not found.\n func get(digest: String) async throws -> Content?\n\n /// Retrieves a specific content metadata type based on the digest string.\n /// Returns `nil` if the requested digest is not found.\n func get(digest: String) async throws -> T?\n\n /// Remove a list of digests in the content store.\n @discardableResult\n func delete(digests: [String]) async throws -> ([String], UInt64)\n\n /// Removes all content from the store except for the digests in the provided list.\n @discardableResult\n func delete(keeping: [String]) async throws -> ([String], UInt64)\n\n /// Creates a transactional write to the content store.\n /// The function takes a closure given a temporary `URL` of the base directory which all contents should be written to.\n /// This is transaction write where any failed operation in the closure (caught exception) will result in all contents written\n /// in the closure to be deleted.\n ///\n /// If the closure succeeds, then all the content that have been written to the temporary `URL` will be moved into the actual\n /// blobs path of the content store.\n @discardableResult\n func ingest(_ body: @Sendable @escaping (URL) async throws -> Void) async throws -> [String]\n\n /// Creates a new ingest session and returns the session ID and temporary ingest directory corresponding to the session.\n /// The contents from the ingest directory are processed and moved into the content store once the session is marked complete.\n /// This can be done by invoking the `completeIngestSession` method with the returned session ID.\n func newIngestSession() async throws -> (id: String, ingestDir: URL)\n\n /// Completes a previously started ingest session corresponding to `id`.\n /// The contents from the ingest directory from the session are moved into the content store atomically.\n /// Any failure encountered will result in a transaction failure causing none of the contents to be ingested into the store.\n @discardableResult\n func completeIngestSession(_ id: String) async throws -> [String]\n\n /// Cancels a previously started ingest session corresponding to `id`.\n /// The contents from the ingest directory corresponding to the session are removed.\n func cancelIngestSession(_ id: String) async throws\n}\n"], ["/containerization/Sources/ContainerizationOS/Keychain/KeychainQuery.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\n\n/// Holds the result of a query to the keychain.\npublic struct KeychainQueryResult {\n public var account: String\n public var data: String\n public var modifiedDate: Date\n public var createdDate: Date\n}\n\n/// Type that facilitates interacting with the macOS keychain.\npublic struct KeychainQuery {\n public init() {}\n\n /// Save a value to the keychain.\n public func save(id: String, host: String, user: String, token: String) throws {\n if try exists(id: id, host: host) {\n try delete(id: id, host: host)\n }\n\n guard let tokenEncoded = token.data(using: String.Encoding.utf8) else {\n throw Self.Error.invalidTokenConversion\n }\n let query: [String: Any] = [\n kSecClass as String: kSecClassInternetPassword,\n kSecAttrSecurityDomain as String: id,\n kSecAttrServer as String: host,\n kSecAttrAccount as String: user,\n kSecValueData as String: tokenEncoded,\n kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock,\n kSecAttrSynchronizable as String: false,\n ]\n let status = SecItemAdd(query as CFDictionary, nil)\n guard status == errSecSuccess else { throw Self.Error.unhandledError(status: status) }\n }\n\n /// Delete a value from the keychain.\n public func delete(id: String, host: String) throws {\n let query: [String: Any] = [\n kSecClass as String: kSecClassInternetPassword,\n kSecAttrSecurityDomain as String: id,\n kSecAttrServer as String: host,\n kSecMatchLimit as String: kSecMatchLimitOne,\n ]\n let status = SecItemDelete(query as CFDictionary)\n guard status == errSecSuccess || status == errSecItemNotFound else {\n throw Self.Error.unhandledError(status: status)\n }\n }\n\n /// Retrieve a value from the keychain.\n public func get(id: String, host: String) throws -> KeychainQueryResult? {\n let query: [String: Any] = [\n kSecClass as String: kSecClassInternetPassword,\n kSecAttrSecurityDomain as String: id,\n kSecAttrServer as String: host,\n kSecReturnAttributes as String: true,\n kSecMatchLimit as String: kSecMatchLimitOne,\n kSecReturnData as String: true,\n ]\n var item: CFTypeRef?\n let status = SecItemCopyMatching(query as CFDictionary, &item)\n let exists = try isQuerySuccessful(status)\n if !exists {\n return nil\n }\n\n guard let fetched = item as? [String: Any] else {\n throw Self.Error.unexpectedDataFetched\n }\n guard let data = fetched[kSecValueData as String] as? Data else {\n throw Self.Error.keyNotPresent(key: kSecValueData as String)\n }\n guard let decodedData = String(data: data, encoding: String.Encoding.utf8) else {\n throw Self.Error.unexpectedDataFetched\n }\n guard let account = fetched[kSecAttrAccount as String] as? String else {\n throw Self.Error.keyNotPresent(key: kSecAttrAccount as String)\n }\n guard let modifiedDate = fetched[kSecAttrModificationDate as String] as? Date else {\n throw Self.Error.keyNotPresent(key: kSecAttrModificationDate as String)\n }\n guard let createdDate = fetched[kSecAttrCreationDate as String] as? Date else {\n throw Self.Error.keyNotPresent(key: kSecAttrCreationDate as String)\n }\n return KeychainQueryResult(\n account: account,\n data: decodedData,\n modifiedDate: modifiedDate,\n createdDate: createdDate\n )\n }\n\n private func isQuerySuccessful(_ status: Int32) throws -> Bool {\n guard status != errSecItemNotFound else {\n return false\n }\n guard status == errSecSuccess else {\n throw Self.Error.unhandledError(status: status)\n }\n return true\n }\n\n /// Check if a value exists in the keychain.\n public func exists(id: String, host: String) throws -> Bool {\n let query: [String: Any] = [\n kSecClass as String: kSecClassInternetPassword,\n kSecAttrSecurityDomain as String: id,\n kSecAttrServer as String: host,\n kSecReturnAttributes as String: true,\n kSecMatchLimit as String: kSecMatchLimitOne,\n kSecReturnData as String: false,\n ]\n\n let status = SecItemCopyMatching(query as CFDictionary, nil)\n return try isQuerySuccessful(status)\n }\n}\n\nextension KeychainQuery {\n public enum Error: Swift.Error {\n case unhandledError(status: Int32)\n case unexpectedDataFetched\n case keyNotPresent(key: String)\n case invalidTokenConversion\n }\n}\n#endif\n"], ["/containerization/Sources/ContainerizationOCI/Manifest.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// Source: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/manifest.go\n\nimport Foundation\n\n/// Manifest provides `application/vnd.oci.image.manifest.v1+json` mediatype structure when marshalled to JSON.\npublic struct Manifest: Codable, Sendable {\n /// `schemaVersion` is the image manifest schema that this image follows.\n public let schemaVersion: Int\n\n /// `mediaType` specifies the type of this document data structure, e.g. `application/vnd.oci.image.manifest.v1+json`.\n public let mediaType: String?\n\n /// `config` references a configuration object for a container, by digest.\n /// The referenced configuration object is a JSON blob that the runtime uses to set up the container.\n public let config: Descriptor\n\n /// `layers` is an indexed list of layers referenced by the manifest.\n public let layers: [Descriptor]\n\n /// `annotations` contains arbitrary metadata for the image manifest.\n public let annotations: [String: String]?\n\n public init(\n schemaVersion: Int = 2, mediaType: String = MediaTypes.imageManifest, config: Descriptor, layers: [Descriptor],\n annotations: [String: String]? = nil\n ) {\n self.schemaVersion = schemaVersion\n self.mediaType = mediaType\n self.config = config\n self.layers = layers\n self.annotations = annotations\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/UInt8+DataBinding.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension ArraySlice {\n package func hexEncodedString() -> String {\n self.map { String(format: \"%02hhx\", $0) }.joined()\n }\n}\n\nextension [UInt8] {\n package func hexEncodedString() -> String {\n self.map { String(format: \"%02hhx\", $0) }.joined()\n }\n\n package mutating func bind(as type: T.Type, offset: Int = 0, size: Int? = nil) -> UnsafeMutablePointer? {\n guard self.count >= (size ?? MemoryLayout.size) + offset else {\n return nil\n }\n\n return self.withUnsafeMutableBytes { $0.baseAddress?.advanced(by: offset).assumingMemoryBound(to: T.self) }\n }\n\n package mutating func copyIn(as type: T.Type, value: T, offset: Int = 0, size: Int? = nil) -> Int? {\n let size = size ?? MemoryLayout.size\n guard self.count >= size - offset else {\n return nil\n }\n\n return self.withUnsafeMutableBytes {\n $0.baseAddress?.advanced(by: offset).assumingMemoryBound(to: T.self).pointee = value\n return offset + MemoryLayout.size\n }\n }\n\n package mutating func copyOut(as type: T.Type, offset: Int = 0, size: Int? = nil) -> (Int, T)? {\n guard self.count >= (size ?? MemoryLayout.size) - offset else {\n return nil\n }\n\n return self.withUnsafeMutableBytes {\n guard let value = $0.baseAddress?.advanced(by: offset).assumingMemoryBound(to: T.self).pointee else {\n return nil\n }\n return (offset + MemoryLayout.size, value)\n }\n }\n\n package mutating func copyIn(buffer: [UInt8], offset: Int = 0) -> Int? {\n guard offset + buffer.count <= self.count else {\n return nil\n }\n\n self[offset.. Int? {\n guard offset + buffer.count <= self.count else {\n return nil\n }\n\n buffer[0.. AsyncStream {\n .init { cont in\n self.handle.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n self.handle.readabilityHandler = nil\n cont.finish()\n return\n }\n cont.yield(data)\n }\n }\n }\n}\n\nextension Terminal: Writer {}\n"], ["/containerization/Sources/ContainerizationNetlink/NetlinkSocket.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A protocol for interacting with a netlink socket.\npublic protocol NetlinkSocket {\n var pid: UInt32 { get }\n func send(buf: UnsafeRawPointer!, len: Int, flags: Int32) throws -> Int\n func recv(buf: UnsafeMutableRawPointer!, len: Int, flags: Int32) throws -> Int\n}\n\n/// A netlink socket provider.\npublic typealias NetlinkSocketProvider = () throws -> any NetlinkSocket\n\n/// Errors thrown when interacting with a netlink socket.\npublic enum NetlinkSocketError: Swift.Error, CustomStringConvertible, Equatable {\n case socketFailure(rc: Int32)\n case bindFailure(rc: Int32)\n case sendFailure(rc: Int32)\n case recvFailure(rc: Int32)\n case notImplemented\n\n /// The description of the errors.\n public var description: String {\n switch self {\n case .socketFailure(let rc):\n return \"could not create netlink socket, rc = \\(rc)\"\n case .bindFailure(let rc):\n return \"could not bind netlink socket, rc = \\(rc)\"\n case .sendFailure(let rc):\n return \"could not send netlink packet, rc = \\(rc)\"\n case .recvFailure(let rc):\n return \"could not receive netlink packet, rc = \\(rc)\"\n case .notImplemented:\n return \"socket function not implemented for platform\"\n }\n }\n}\n\n#if canImport(Musl)\nimport Musl\nlet osSocket = Musl.socket\nlet osBind = Musl.bind\nlet osSend = Musl.send\nlet osRecv = Musl.recv\n\n/// A default implementation of `NetlinkSocket`.\npublic class DefaultNetlinkSocket: NetlinkSocket {\n private let sockfd: Int32\n\n /// The process identifier of the process creating this socket.\n public let pid: UInt32\n\n /// Creates a new instance.\n public init() throws {\n pid = UInt32(getpid())\n sockfd = osSocket(Int32(AddressFamily.AF_NETLINK), SocketType.SOCK_RAW, NetlinkProtocol.NETLINK_ROUTE)\n guard sockfd >= 0 else {\n throw NetlinkSocketError.socketFailure(rc: errno)\n }\n\n let addr = SockaddrNetlink(family: AddressFamily.AF_NETLINK, pid: pid)\n var buffer = [UInt8](repeating: 0, count: SockaddrNetlink.size)\n _ = try addr.appendBuffer(&buffer, offset: 0)\n guard let ptr = buffer.bind(as: sockaddr.self, size: buffer.count) else {\n throw NetlinkSocketError.bindFailure(rc: 0)\n }\n guard osBind(sockfd, ptr, UInt32(buffer.count)) >= 0 else {\n throw NetlinkSocketError.bindFailure(rc: errno)\n }\n }\n\n deinit {\n close(sockfd)\n }\n\n /// Sends a request to a netlink socket.\n /// Returns the number of bytes sent.\n /// - Parameters:\n /// - buf: The buffer to send.\n /// - len: The length of the buffer to send.\n /// - flags: The send flags.\n public func send(buf: UnsafeRawPointer!, len: Int, flags: Int32) throws -> Int {\n let count = osSend(sockfd, buf, len, flags)\n guard count >= 0 else {\n throw NetlinkSocketError.sendFailure(rc: errno)\n }\n\n return count\n }\n\n /// Receives a response from a netlink socket.\n /// Returns the number of bytes received.\n /// - Parameters:\n /// - buf: The buffer to receive into.\n /// - len: The maximum number of bytes to receive.\n /// - flags: The receive flags.\n public func recv(buf: UnsafeMutableRawPointer!, len: Int, flags: Int32) throws -> Int {\n let count = osRecv(sockfd, buf, len, flags)\n guard count >= 0 else {\n throw NetlinkSocketError.recvFailure(rc: errno)\n }\n\n return count\n }\n}\n#else\npublic class DefaultNetlinkSocket: NetlinkSocket {\n public var pid: UInt32 { 0 }\n\n public init() throws {}\n\n public func send(buf: UnsafeRawPointer!, len: Int, flags: Int32) throws -> Int {\n throw NetlinkSocketError.notImplemented\n }\n\n public func recv(buf: UnsafeMutableRawPointer!, len: Int, flags: Int32) throws -> Int {\n throw NetlinkSocketError.notImplemented\n }\n}\n#endif\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension EXT4.InodeFlag {\n public static func | (lhs: Self, rhs: Self) -> Self {\n Self(rawValue: lhs.rawValue | rhs.rawValue)\n }\n\n public static func | (lhs: Self, rhs: Self) -> UInt32 {\n lhs.rawValue | rhs.rawValue\n }\n\n public static func | (lhs: Self, rhs: UInt32) -> UInt32 {\n lhs.rawValue | rhs\n }\n}\n\nextension EXT4.CompatFeature {\n public static func | (lhs: Self, rhs: Self) -> Self {\n EXT4.CompatFeature(rawValue: lhs.rawValue | rhs.rawValue)\n }\n\n public static func | (lhs: Self, rhs: Self) -> UInt32 {\n lhs.rawValue | rhs.rawValue\n }\n}\n\nextension EXT4.IncompatFeature {\n public static func | (lhs: Self, rhs: Self) -> Self {\n EXT4.IncompatFeature(rawValue: lhs.rawValue | rhs.rawValue)\n }\n\n public static func | (lhs: Self, rhs: Self) -> UInt32 {\n lhs.rawValue | rhs.rawValue\n }\n}\n\nextension EXT4.RoCompatFeature {\n public static func | (lhs: Self, rhs: Self) -> Self {\n EXT4.RoCompatFeature(rawValue: lhs.rawValue | rhs.rawValue)\n }\n\n public static func | (lhs: Self, rhs: Self) -> UInt32 {\n lhs.rawValue | rhs.rawValue\n }\n}\n\nextension EXT4.FileModeFlag {\n public static func | (lhs: Self, rhs: Self) -> Self {\n Self(rawValue: lhs.rawValue | rhs.rawValue)\n }\n\n public static func | (lhs: Self, rhs: Self) -> UInt16 {\n lhs.rawValue | rhs.rawValue\n }\n}\n\nextension EXT4.XAttrEntry {\n init(using bytes: [UInt8]) throws {\n guard bytes.count == 16 else {\n throw EXT4.Error.invalidXattrEntry\n }\n nameLength = bytes[0]\n nameIndex = bytes[1]\n let rawValue = Array(bytes[2...3])\n valueOffset = UInt16(littleEndian: rawValue.withUnsafeBytes { $0.load(as: UInt16.self) })\n\n let rawValueInum = Array(bytes[4...7])\n valueInum = UInt32(littleEndian: rawValueInum.withUnsafeBytes { $0.load(as: UInt32.self) })\n\n let rawSize = Array(bytes[8...11])\n valueSize = UInt32(littleEndian: rawSize.withUnsafeBytes { $0.load(as: UInt32.self) })\n\n let rawHash = Array(bytes[12...])\n hash = UInt32(littleEndian: rawHash.withUnsafeBytes { $0.load(as: UInt32.self) })\n }\n}\n\nextension EXT4 {\n static func tupleToArray(_ tuple: T) -> [UInt8] {\n let reflection = Mirror(reflecting: tuple)\n return reflection.children.compactMap { $0.value as? UInt8 }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/File.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Trivial type to discover information about a given file (uid, gid, mode...).\npublic struct File: Sendable {\n /// `File` errors.\n public enum Error: Swift.Error, CustomStringConvertible {\n case errno(_ e: Int32)\n\n public var description: String {\n switch self {\n case .errno(let code):\n return \"errno \\(code)\"\n }\n }\n }\n\n /// Returns a `FileInfo` struct with information about the file.\n /// - Parameters:\n /// - url: The path to the file.\n public static func info(_ url: URL) throws -> FileInfo {\n try info(url.path)\n }\n\n /// Returns a `FileInfo` struct with information about the file.\n /// - Parameters:\n /// - path: The path to the file as a string.\n public static func info(_ path: String) throws -> FileInfo {\n var st = stat()\n guard stat(path, &st) == 0 else {\n throw Error.errno(errno)\n }\n return FileInfo(path, stat: st)\n }\n}\n\n/// `FileInfo` holds and provides easy access to stat(2) data\n/// for a file.\npublic struct FileInfo: Sendable {\n private let _stat_t: Foundation.stat\n private let _path: String\n\n init(_ path: String, stat: stat) {\n self._path = path\n self._stat_t = stat\n }\n\n /// mode_t for the file.\n public var mode: mode_t {\n self._stat_t.st_mode\n }\n\n /// The files uid.\n public var uid: Int {\n Int(self._stat_t.st_uid)\n }\n\n /// The files gid.\n public var gid: Int {\n Int(self._stat_t.st_gid)\n }\n\n /// The filesystem ID the file belongs to.\n public var dev: Int {\n Int(self._stat_t.st_dev)\n }\n\n /// The files inode number.\n public var ino: Int {\n Int(self._stat_t.st_ino)\n }\n\n /// The size of the file.\n public var size: Int {\n Int(self._stat_t.st_size)\n }\n\n /// The path to the file.\n public var path: String {\n self._path\n }\n\n /// Returns if the file is a directory.\n public var isDirectory: Bool {\n mode & S_IFMT == S_IFDIR\n }\n\n /// Returns if the file is a pipe.\n public var isPipe: Bool {\n mode & S_IFMT == S_IFIFO\n }\n\n /// Returns if the file is a socket.\n public var isSocket: Bool {\n mode & S_IFMT == S_IFSOCK\n }\n\n /// Returns if the file is a link.\n public var isLink: Bool {\n mode & S_IFMT == S_IFLNK\n }\n\n /// Returns if the file is a regular file.\n public var isRegularFile: Bool {\n mode & S_IFMT == S_IFREG\n }\n\n /// Returns if the file is a block device.\n public var isBlock: Bool {\n mode & S_IFMT == S_IFBLK\n }\n\n /// Returns if the file is a character device.\n public var isChar: Bool {\n mode & S_IFMT == S_IFCHR\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/BinaryInteger+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension BinaryInteger {\n private func toUnsignedMemoryAmount(_ amount: UInt64) -> UInt64 {\n guard self > 0 else {\n fatalError(\"encountered negative number during conversion to memory amount\")\n }\n let val = UInt64(self)\n let (newVal, overflow) = val.multipliedReportingOverflow(by: amount)\n guard !overflow else {\n fatalError(\"UInt64 overflow when converting to memory amount\")\n }\n return newVal\n }\n\n public func kib() -> UInt64 {\n self.toUnsignedMemoryAmount(1 << 10)\n }\n\n public func mib() -> UInt64 {\n self.toUnsignedMemoryAmount(1 << 20)\n }\n\n public func gib() -> UInt64 {\n self.toUnsignedMemoryAmount(1 << 30)\n }\n\n public func tib() -> UInt64 {\n self.toUnsignedMemoryAmount(1 << 40)\n }\n\n public func pib() -> UInt64 {\n self.toUnsignedMemoryAmount(1 << 50)\n }\n}\n"], ["/containerization/Sources/Containerization/AttachedFilesystem.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport ContainerizationOCI\n\n/// A filesystem that was attached and able to be mounted inside the runtime environment.\npublic struct AttachedFilesystem: Sendable {\n /// The type of the filesystem.\n public var type: String\n /// The path to the filesystem within a sandbox.\n public var source: String\n /// Destination when mounting the filesystem inside a sandbox.\n public var destination: String\n /// The options to use when mounting the filesystem.\n public var options: [String]\n\n #if os(macOS)\n public init(mount: Mount, allocator: any AddressAllocator) throws {\n switch mount.type {\n case \"virtiofs\":\n let name = try hashMountSource(source: mount.source)\n self.source = name\n case \"ext4\":\n let char = try allocator.allocate()\n self.source = \"/dev/vd\\(char)\"\n default:\n self.source = mount.source\n }\n self.type = mount.type\n self.options = mount.options\n self.destination = mount.destination\n }\n #endif\n}\n"], ["/containerization/Sources/Containerization/Container.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// The core protocol container implementations must implement.\npublic protocol Container {\n /// ID for the container.\n var id: String { get }\n /// The amount of cpus assigned to the container.\n var cpus: Int { get }\n /// The memory in bytes assigned to the container.\n var memoryInBytes: UInt64 { get }\n /// The network interfaces assigned to the container.\n var interfaces: [any Interface] { get }\n}\n"], ["/containerization/Sources/ContainerizationArchive/TempDir.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport Foundation\n\ninternal func createTemporaryDirectory(baseName: String) -> URL? {\n let url = FileManager.default.uniqueTemporaryDirectory().appendingPathComponent(\n \"\\(baseName).XXXXXX\")\n guard let templatePathData = (url.absoluteURL.path as NSString).utf8String else {\n return nil\n }\n\n let pathData = UnsafeMutablePointer(mutating: templatePathData)\n mkdtemp(pathData)\n\n return URL(fileURLWithPath: String(cString: pathData), isDirectory: true)\n}\n"], ["/containerization/Sources/ContainerizationOCI/Descriptor.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// Source: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/descriptor.go\n\nimport Foundation\n\n/// Descriptor describes the disposition of targeted content.\n/// This structure provides `application/vnd.oci.descriptor.v1+json` mediatype\n/// when marshalled to JSON.\npublic struct Descriptor: Codable, Sendable, Equatable {\n /// mediaType is the media type of the object this schema refers to.\n public let mediaType: String\n\n /// digest is the digest of the targeted content.\n public let digest: String\n\n /// size specifies the size in bytes of the blob.\n public let size: Int64\n\n /// urls specifies a list of URLs from which this object MAY be downloaded.\n public let urls: [String]?\n\n /// annotations contains arbitrary metadata relating to the targeted content.\n public var annotations: [String: String]?\n\n /// platform describes the platform which the image in the manifest runs on.\n ///\n /// This should only be used when referring to a manifest.\n public var platform: Platform?\n\n public init(\n mediaType: String, digest: String, size: Int64, urls: [String]? = nil, annotations: [String: String]? = nil,\n platform: Platform? = nil\n ) {\n self.mediaType = mediaType\n self.digest = digest\n self.size = size\n self.urls = urls\n self.annotations = annotations\n self.platform = platform\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/AddressAllocator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Conforming objects can allocate and free various address types.\npublic protocol AddressAllocator: Sendable {\n associatedtype AddressType: Sendable\n\n /// Allocate a new address.\n func allocate() throws -> AddressType\n\n /// Attempt to reserve a specific address.\n func reserve(_ address: AddressType) throws\n\n /// Free an allocated address.\n func release(_ address: AddressType) throws\n\n /// If no addresses are allocated, prevent future allocations and return true.\n func disableAllocator() -> Bool\n}\n\n/// Errors that a type implementing AddressAllocator should throw.\npublic enum AllocatorError: Swift.Error, CustomStringConvertible, Equatable {\n case allocatorDisabled\n case allocatorFull\n case alreadyAllocated(_ address: String)\n case invalidAddress(_ index: String)\n case invalidArgument(_ msg: String)\n case invalidIndex(_ index: Int)\n case notAllocated(_ address: String)\n case rangeExceeded\n\n public var description: String {\n switch self {\n case .allocatorDisabled:\n return \"the allocator is shutting down\"\n case .allocatorFull:\n return \"no free indices are available for allocation\"\n case .alreadyAllocated(let address):\n return \"cannot choose already-allocated address \\(address)\"\n case .invalidAddress(let address):\n return \"cannot create index using address \\(address)\"\n case .invalidArgument(let msg):\n return \"invalid argument: \\(msg)\"\n case .invalidIndex(let index):\n return \"cannot create address using index \\(index)\"\n case .notAllocated(let address):\n return \"cannot free unallocated address \\(address)\"\n case .rangeExceeded:\n return \"cannot create allocator that overflows maximum address value\"\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Syscall.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if canImport(Musl)\nimport Musl\n#elseif canImport(Glibc)\nimport Glibc\n#elseif canImport(Darwin)\nimport Darwin\n#else\n#error(\"retryingSyscall not supported on this platform.\")\n#endif\n\n/// Helper type to deal with running system calls.\npublic struct Syscall {\n /// Retry a syscall on EINTR.\n public static func retrying(_ closure: () -> T) -> T {\n while true {\n let res = closure()\n if res == -1 && errno == EINTR {\n continue\n }\n return res\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Ptr.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension EXT4 {\n class Ptr {\n let underlying: UnsafeMutablePointer\n private var capacity: Int\n private var initialized: Bool\n private var allocated: Bool\n\n var pointee: T {\n underlying.pointee\n }\n\n init(capacity: Int) {\n self.underlying = UnsafeMutablePointer.allocate(capacity: capacity)\n self.capacity = capacity\n self.allocated = true\n self.initialized = false\n }\n\n static func allocate(capacity: Int) -> Ptr {\n Ptr(capacity: capacity)\n }\n\n func initialize(to value: T) {\n guard self.allocated else {\n return\n }\n if self.initialized {\n self.underlying.deinitialize(count: self.capacity)\n }\n self.underlying.initialize(to: value)\n self.allocated = true\n self.initialized = true\n }\n\n func deallocate() {\n guard self.allocated else {\n return\n }\n self.underlying.deallocate()\n self.allocated = false\n self.initialized = false\n }\n\n func deinitialize(count: Int) {\n guard self.allocated else {\n return\n }\n guard self.initialized else {\n return\n }\n self.underlying.deinitialize(count: count)\n self.initialized = false\n self.allocated = true\n }\n\n func move() -> T {\n self.initialized = false\n self.allocated = true\n return self.underlying.move()\n }\n\n deinit {\n self.deinitialize(count: self.capacity)\n self.deallocate()\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Sysctl.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Helper type to deal with system control functionalities.\npublic struct Sysctl {\n #if os(macOS)\n /// Simple `sysctlbyname` wrapper.\n public static func byName(_ name: String) throws -> Int64 {\n var num: Int64 = 0\n var size = MemoryLayout.size\n if sysctlbyname(name, &num, &size, nil, 0) != 0 {\n throw POSIXError.fromErrno()\n }\n return num\n }\n #endif\n}\n"], ["/containerization/Sources/ContainerizationOS/Reaper.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A process reaper that returns exited processes along\n/// with their exit status.\npublic struct Reaper {\n /// Process's pid and exit status.\n typealias Exit = (pid: Int32, status: Int32)\n\n /// Reap all pending processes and return the pid and exit status.\n public static func reap() -> [Int32: Int32] {\n var reaped = [Int32: Int32]()\n while true {\n guard let exit = wait() else {\n return reaped\n }\n reaped[exit.pid] = exit.status\n }\n return reaped\n }\n\n /// Returns the exit status of the last process that exited.\n /// nil is returned when no pending processes exist.\n private static func wait() -> Exit? {\n var rus = rusage()\n var ws = Int32()\n\n let pid = wait4(-1, &ws, WNOHANG, &rus)\n if pid <= 0 {\n return nil\n }\n return (pid: pid, status: Command.toExitStatus(ws))\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/Content.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport Crypto\nimport Foundation\nimport NIOCore\n\n/// Protocol for defining a single OCI content\npublic protocol Content: Sendable {\n /// URL to the content\n var path: URL { get }\n\n /// sha256 of content\n func digest() throws -> SHA256.Digest\n\n /// Size of content\n func size() throws -> UInt64\n\n /// Data representation of entire content\n func data() throws -> Data\n\n /// Data representation partial content\n func data(offset: UInt64, length: Int) throws -> Data?\n\n /// Decode the content into an object\n func decode() throws -> T where T: Decodable\n}\n\n/// Protocol defining methods to fetch and push OCI content\npublic protocol ContentClient: Sendable {\n func fetch(name: String, descriptor: Descriptor) async throws -> T\n\n func fetchBlob(name: String, descriptor: Descriptor, into file: URL, progress: ProgressHandler?) async throws -> (Int64, SHA256Digest)\n\n func fetchData(name: String, descriptor: Descriptor) async throws -> Data\n\n func push(\n name: String,\n ref: String,\n descriptor: Descriptor,\n streamGenerator: () throws -> T,\n progress: ProgressHandler?\n ) async throws where T.Element == ByteBuffer\n\n}\n"], ["/containerization/Sources/Containerization/SystemPlatform.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOCI\n\n/// `SystemPlatform` describes an operating system and architecture pair.\n/// This is primarily used to choose what kind of OCI image to pull from a\n/// registry.\npublic struct SystemPlatform: Sendable, Codable {\n public enum OS: String, CaseIterable, Sendable, Codable {\n case linux\n case darwin\n }\n public let os: OS\n\n public enum Architecture: String, CaseIterable, Sendable, Codable {\n case arm64\n case amd64\n }\n public let architecture: Architecture\n\n public func ociPlatform() -> ContainerizationOCI.Platform {\n ContainerizationOCI.Platform(arch: architecture.rawValue, os: os.rawValue)\n }\n\n public static var linuxArm: SystemPlatform { .init(os: .linux, architecture: .arm64) }\n public static var linuxAmd: SystemPlatform { .init(os: .linux, architecture: .amd64) }\n}\n"], ["/containerization/Sources/Containerization/Hash.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\n\nimport Crypto\nimport ContainerizationError\n\nfunc hashMountSource(source: String) throws -> String {\n guard let data = source.data(using: .utf8) else {\n throw ContainerizationError(.invalidArgument, message: \"\\(source) could not be converted to Data\")\n }\n return String(SHA256.hash(data: data).encoded.prefix(36))\n}\n\n#endif\n"], ["/containerization/Sources/ContainerizationOCI/FileManager+Size.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension FileManager {\n func fileSize(atPath path: String) -> Int64? {\n do {\n let attributes = try attributesOfItem(atPath: path)\n guard let fileSize = attributes[.size] as? NSNumber else {\n return nil\n }\n return fileSize.int64Value\n } catch {\n return nil\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/FileManager+Temporary.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension FileManager {\n /// Returns a unique temporary directory to use.\n public func uniqueTemporaryDirectory(create: Bool = true) -> URL {\n let tempDirectoryURL = temporaryDirectory\n let uniqueDirectoryURL = tempDirectoryURL.appendingPathComponent(UUID().uuidString)\n if create {\n try? createDirectory(at: uniqueDirectoryURL, withIntermediateDirectories: true, attributes: nil)\n }\n return uniqueDirectoryURL\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/URL+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension URL {\n /// Returns the unescaped absolutePath of a URL joined by separator.\n public func absolutePath() -> String {\n #if os(macOS)\n return self.path(percentEncoded: false)\n #else\n return self.path\n #endif\n }\n\n /// Returns the domain name of a registry.\n public var domain: String? {\n guard let host = self.absoluteString.split(separator: \":\").first else {\n return nil\n }\n return String(host)\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/Authentication.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Abstraction for returning a token needed for logging into an OCI compliant registry.\npublic protocol Authentication: Sendable {\n func token() async throws -> String\n}\n\n/// Type representing authentication information for client to access the registry.\npublic struct BasicAuthentication: Authentication {\n /// The username for the authentication.\n let username: String\n /// The password or identity token for the user.\n let password: String\n\n public init(username: String, password: String) {\n self.username = username\n self.password = password\n }\n\n /// Get a token using the provided username and password. This will be a\n /// base64 encoded string of the username and password delimited by a colon.\n public func token() async throws -> String {\n let credentials = \"\\(username):\\(password)\"\n if let authenticationData = credentials.data(using: .utf8)?.base64EncodedString() {\n return \"Basic \\(authenticationData)\"\n }\n throw Error.invalidCredentials\n }\n\n /// `BasicAuthentication` errors.\n public enum Error: Swift.Error {\n case invalidCredentials\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Index.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// Source: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/index.go\n\nimport Foundation\n\n/// Index references manifests for various platforms.\n/// This structure provides `application/vnd.oci.image.index.v1+json` mediatype when marshalled to JSON.\npublic struct Index: Codable, Sendable {\n /// schemaVersion is the image manifest schema that this image follows\n public let schemaVersion: Int\n\n /// mediaType specifies the type of this document data structure e.g. `application/vnd.oci.image.index.v1+json`\n public let mediaType: String\n\n /// manifests references platform specific manifests.\n public var manifests: [Descriptor]\n\n /// annotations contains arbitrary metadata for the image index.\n public var annotations: [String: String]?\n\n public init(\n schemaVersion: Int = 2, mediaType: String = MediaTypes.index, manifests: [Descriptor],\n annotations: [String: String]? = nil\n ) {\n self.schemaVersion = schemaVersion\n self.mediaType = mediaType\n self.manifests = manifests\n self.annotations = annotations\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/String+Extension.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension String {\n /// Removes any prefix (sha256:) from a digest string.\n public var trimmingDigestPrefix: String {\n let split = self.split(separator: \":\")\n if split.count == 2 {\n return String(split[1])\n }\n return self\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/Integer+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension UInt64 {\n public var lo: UInt32 {\n UInt32(self & 0xffff_ffff)\n }\n\n public var hi: UInt32 {\n UInt32(self >> 32)\n }\n\n public static func - (lhs: Self, rhs: UInt32) -> UInt64 {\n lhs - UInt64(rhs)\n }\n\n public static func % (lhs: Self, rhs: UInt32) -> UInt64 {\n lhs % UInt64(rhs)\n }\n\n public static func / (lhs: Self, rhs: UInt32) -> UInt32 {\n (lhs / UInt64(rhs)).lo\n }\n\n public static func * (lhs: Self, rhs: UInt32) -> UInt64 {\n lhs * UInt64(rhs)\n }\n\n public static func * (lhs: Self, rhs: Int) -> UInt64 {\n lhs * UInt64(rhs)\n }\n}\n\nextension UInt32 {\n public var lo: UInt16 {\n UInt16(self & 0xffff)\n }\n\n public var hi: UInt16 {\n UInt16(self >> 16)\n }\n\n public static func + (lhs: Self, rhs: Int.IntegerLiteralType) -> UInt32 {\n lhs + UInt32(rhs)\n }\n\n public static func - (lhs: Self, rhs: Int.IntegerLiteralType) -> UInt32 {\n lhs - UInt32(rhs)\n }\n\n public static func / (lhs: Self, rhs: Int.IntegerLiteralType) -> UInt32 {\n lhs / UInt32(rhs)\n }\n\n public static func - (lhs: Self, rhs: UInt16) -> UInt32 {\n lhs - UInt32(rhs)\n }\n\n public static func * (lhs: Self, rhs: Int.IntegerLiteralType) -> Int {\n Int(lhs) * rhs\n }\n}\n\nextension Int {\n public static func + (lhs: Self, rhs: UInt32) -> Int {\n lhs + Int(rhs)\n }\n\n public static func + (lhs: Self, rhs: UInt32) -> UInt32 {\n UInt32(lhs) + rhs\n }\n}\n\nextension UInt16 {\n func isDir() -> Bool {\n self & EXT4.FileModeFlag.TypeMask.rawValue == EXT4.FileModeFlag.S_IFDIR.rawValue\n }\n\n func isLink() -> Bool {\n self & EXT4.FileModeFlag.TypeMask.rawValue == EXT4.FileModeFlag.S_IFLNK.rawValue\n }\n\n func isReg() -> Bool {\n self & EXT4.FileModeFlag.TypeMask.rawValue == EXT4.FileModeFlag.S_IFREG.rawValue\n }\n\n func fileType() -> UInt8 {\n typealias FMode = EXT4.FileModeFlag\n typealias FileType = EXT4.FileType\n switch self & FMode.TypeMask.rawValue {\n case FMode.S_IFREG.rawValue:\n return FileType.regular.rawValue\n case FMode.S_IFDIR.rawValue:\n return FileType.directory.rawValue\n case FMode.S_IFCHR.rawValue:\n return FileType.character.rawValue\n case FMode.S_IFBLK.rawValue:\n return FileType.block.rawValue\n case FMode.S_IFIFO.rawValue:\n return FileType.fifo.rawValue\n case FMode.S_IFSOCK.rawValue:\n return FileType.socket.rawValue\n case FMode.S_IFLNK.rawValue:\n return FileType.symbolicLink.rawValue\n default:\n return FileType.unknown.rawValue\n }\n }\n}\n\nextension [UInt8] {\n var allZeros: Bool {\n for num in self where num != 0 {\n return false\n }\n return true\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/State.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum ContainerState: String, Codable, Sendable {\n case creating\n case created\n case running\n case stopped\n}\n\npublic struct State: Codable, Sendable {\n public init(\n version: String,\n id: String,\n status: ContainerState,\n pid: Int,\n bundle: String,\n annotations: [String: String]?\n ) {\n self.ociVersion = version\n self.id = id\n self.status = status\n self.pid = pid\n self.bundle = bundle\n self.annotations = annotations\n }\n\n public init(instance: State) {\n self.ociVersion = instance.ociVersion\n self.id = instance.id\n self.status = instance.status\n self.pid = instance.pid\n self.bundle = instance.bundle\n self.annotations = instance.annotations\n }\n\n public let ociVersion: String\n public let id: String\n public let status: ContainerState\n public let pid: Int\n public let bundle: String\n public var annotations: [String: String]?\n}\n\npublic let seccompFdName: String = \"seccompFd\"\n\npublic struct ContainerProcessState: Codable, Sendable {\n public init(version: String, fds: [String], pid: Int, metadata: String, state: State) {\n self.ociVersion = version\n self.fds = fds\n self.pid = pid\n self.metadata = metadata\n self.state = state\n }\n\n public init(instance: ContainerProcessState) {\n self.ociVersion = instance.ociVersion\n self.fds = instance.fds\n self.pid = instance.pid\n self.metadata = instance.metadata\n self.state = instance.state\n }\n\n public let ociVersion: String\n public var fds: [String]\n public let pid: Int\n public let metadata: String\n public let state: State\n}\n"], ["/containerization/Sources/ContainerizationOCI/MediaType.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// MediaTypes represent all supported OCI image content types for both metadata and layer formats.\n/// Follows all distributable media types in: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/mediatype.go\npublic struct MediaTypes: Codable, Sendable {\n /// Specifies the media type for a content descriptor.\n public static let descriptor = \"application/vnd.oci.descriptor.v1+json\"\n\n /// Specifies the media type for the oci-layout.\n public static let layoutHeader = \"application/vnd.oci.layout.header.v1+json\"\n\n /// Specifies the media type for an image index.\n public static let index = \"application/vnd.oci.image.index.v1+json\"\n\n /// Specifies the media type for an image manifest.\n public static let imageManifest = \"application/vnd.oci.image.manifest.v1+json\"\n\n /// Specifies the media type for the image configuration.\n public static let imageConfig = \"application/vnd.oci.image.config.v1+json\"\n\n /// Specifies the media type for an unused blob containing the value \"{}\".\n public static let emptyJSON = \"application/vnd.oci.empty.v1+json\"\n\n /// Specifies the media type for a Docker image manifest.\n public static let dockerManifest = \"application/vnd.docker.distribution.manifest.v2+json\"\n\n /// Specifies the media type for a Docker image manifest list.\n public static let dockerManifestList = \"application/vnd.docker.distribution.manifest.list.v2+json\"\n\n /// The Docker media type used for image configurations.\n public static let dockerImageConfig = \"application/vnd.docker.container.image.v1+json\"\n\n /// The media type used for layers referenced by the manifest.\n public static let imageLayer = \"application/vnd.oci.image.layer.v1.tar\"\n\n /// The media type used for gzipped layers referenced by the manifest.\n public static let imageLayerGzip = \"application/vnd.oci.image.layer.v1.tar+gzip\"\n\n /// The media type used for zstd compressed layers referenced by the manifest.\n public static let imageLayerZstd = \"application/vnd.oci.image.layer.v1.tar+zstd\"\n\n /// The Docker media type used for uncompressed layers referenced by an image manifest.\n public static let dockerImageLayer = \"application/vnd.docker.image.rootfs.diff.tar\"\n\n /// The Docker media type used for gzipped layers referenced by an image manifest.\n public static let dockerImageLayerGzip = \"application/vnd.docker.image.rootfs.diff.tar.gzip\"\n\n /// The Docker media type used for zstd compressed layers referenced by an image manifest.\n public static let dockerImageLayerZstd = \"application/vnd.docker.image.rootfs.diff.tar.zstd\"\n\n /// The media type used for in-toto attestations blobs.\n public static let inTotoAttestationBlob = \"application/vnd.in-toto+json\"\n}\n"], ["/containerization/Sources/Containerization/VsockConnectionStream.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n#if os(macOS)\nimport Virtualization\n#endif\n\n/// A stream of vsock connections.\npublic final class VsockConnectionStream: NSObject, Sendable {\n /// A stream of connections dialed from the remote.\n public let connections: AsyncStream\n /// The port the connections are for.\n public let port: UInt32\n\n private let cont: AsyncStream.Continuation\n\n public init(port: UInt32) {\n self.port = port\n let (stream, continuation) = AsyncStream.makeStream(of: FileHandle.self)\n self.connections = stream\n self.cont = continuation\n }\n\n public func finish() {\n self.cont.finish()\n }\n}\n\n#if os(macOS)\n\nextension VsockConnectionStream: VZVirtioSocketListenerDelegate {\n public func listener(\n _: VZVirtioSocketListener, shouldAcceptNewConnection conn: VZVirtioSocketConnection,\n from _: VZVirtioSocketDevice\n ) -> Bool {\n let fd = dup(conn.fileDescriptor)\n conn.close()\n\n cont.yield(FileHandle(fileDescriptor: fd, closeOnDealloc: false))\n return true\n }\n}\n\n#endif\n"], ["/containerization/Sources/SendableProperty/Synchronized.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// `Synchronization` will be automatically imported with `SendableProperty`.\n@_exported import Synchronization\n\n/// A synchronization primitive that protects shared mutable state via mutual exclusion.\npublic final class Synchronized: Sendable {\n private let lock: Mutex\n\n private struct State: @unchecked Sendable {\n var value: T\n }\n\n /// Creates a new instance.\n /// - Parameter value: The initial value.\n public init(_ value: T) {\n self.lock = Mutex(State(value: value))\n }\n\n /// Calls the given closure after acquiring the lock and returns its value.\n /// - Parameter body: The body of code to execute while the lock is held.\n public func withLock(_ body: (inout T) throws -> R) rethrows -> R {\n try lock.withLock { state in\n try body(&state.value)\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Pipe+Close.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension Pipe {\n /// Close both sides of the pipe.\n public func close() throws {\n var err: Swift.Error?\n do {\n try self.fileHandleForReading.close()\n } catch {\n err = error\n }\n try self.fileHandleForWriting.close()\n if let err {\n throw err\n }\n }\n\n /// Ensure that both sides of the pipe are set with O_CLOEXEC.\n public func setCloexec() throws {\n if fcntl(self.fileHandleForWriting.fileDescriptor, F_SETFD, FD_CLOEXEC) == -1 {\n throw POSIXError(.init(rawValue: errno)!)\n }\n if fcntl(self.fileHandleForReading.fileDescriptor, F_SETFD, FD_CLOEXEC) == -1 {\n throw POSIXError(.init(rawValue: errno)!)\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/SHA256+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Crypto\nimport Foundation\n\nextension SHA256.Digest {\n /// Returns the digest as a string.\n public var digestString: String {\n let parts = self.description.split(separator: \": \")\n return \"sha256:\\(parts[1])\"\n }\n\n /// Returns the digest without a 'sha256:' prefix.\n public var encoded: String {\n let parts = self.description.split(separator: \": \")\n return String(parts[1])\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/POSIXError+Helpers.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension POSIXError {\n public static func fromErrno() -> POSIXError {\n guard let errCode = POSIXErrorCode(rawValue: errno) else {\n fatalError(\"failed to convert errno to POSIXErrorCode\")\n }\n return POSIXError(errCode)\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Socket/SocketType.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if canImport(Musl)\nimport Musl\n#elseif canImport(Glibc)\nimport Glibc\n#elseif canImport(Darwin)\nimport Darwin\n#else\n#error(\"SocketType not supported on this platform.\")\n#endif\n\n/// Protocol used to describe the family of socket to be created with `Socket`.\npublic protocol SocketType: Sendable, CustomStringConvertible {\n /// The domain for the socket (AF_UNIX, AF_VSOCK etc.)\n var domain: Int32 { get }\n /// The type of socket (SOCK_STREAM).\n var type: Int32 { get }\n\n /// Actions to perform before calling bind(2).\n func beforeBind(fd: Int32) throws\n /// Actions to perform before calling listen(2).\n func beforeListen(fd: Int32) throws\n\n /// Handle accept(2) for an implementation of a socket type.\n func accept(fd: Int32) throws -> (Int32, SocketType)\n /// Provide a sockaddr pointer (by casting a socket specific type like sockaddr_un for example).\n func withSockAddr(_ closure: (_ ptr: UnsafePointer, _ len: UInt32) throws -> Void) throws\n}\n\nextension SocketType {\n public func beforeBind(fd: Int32) {}\n public func beforeListen(fd: Int32) {}\n}\n"], ["/containerization/Sources/Containerization/NATInterface.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic struct NATInterface: Interface {\n public var address: String\n public var gateway: String?\n public var macAddress: String?\n\n public init(address: String, gateway: String?, macAddress: String? = nil) {\n self.address = address\n self.gateway = gateway\n self.macAddress = macAddress\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/AsyncTypes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npackage actor AsyncStore {\n private var _value: T?\n\n package init(_ value: T? = nil) {\n self._value = value\n }\n\n package func get() -> T? {\n self._value\n }\n\n package func set(_ value: T) {\n self._value = value\n }\n}\n\npackage actor AsyncSet {\n private var buffer: Set\n\n package init(_ elements: S) where S.Element == T {\n buffer = Set(elements)\n }\n\n package var count: Int {\n buffer.count\n }\n\n package func insert(_ element: T) {\n buffer.insert(element)\n }\n\n @discardableResult\n package func remove(_ element: T) -> T? {\n buffer.remove(element)\n }\n\n package func contains(_ element: T) -> Bool {\n buffer.contains(element)\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/ProgressEvent.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A progress update event.\npublic struct ProgressEvent: Sendable {\n /// The event name. The possible values:\n /// - `add-items`: Increment the number of processed items by `value`.\n /// - `add-total-items`: Increment the total number of items to process by `value`.\n /// - `add-size`: Increment the size of processed items by `value`.\n /// - `add-total-size`: Increment the total size of items to process by `value`.\n public let event: String\n /// The event value.\n public let value: any Sendable\n\n /// Creates an instance.\n /// - Parameters:\n /// - event: The event name.\n /// - value: The event value.\n public init(event: String, value: any Sendable) {\n self.event = event\n self.value = value\n }\n}\n\n/// The progress update handler.\npublic typealias ProgressHandler = @Sendable (_ events: [ProgressEvent]) async -> Void\n"], ["/containerization/Sources/ContainerizationOCI/AnnotationKeys.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// AnnotationKeys contains a subset of \"dictionary keys\" for commonly used annotations in an OCI Image Descriptor\n/// https://github.com/opencontainers/image-spec/blob/main/annotations.md\npublic struct AnnotationKeys: Codable, Sendable {\n public static let containerizationIndexIndirect = \"com.apple.containerization.index.indirect\"\n public static let containerizationImageName = \"com.apple.containerization.image.name\"\n public static let containerdImageName = \"io.containerd.image.name\"\n public static let openContainersImageName = \"org.opencontainers.image.ref.name\"\n}\n"], ["/containerization/Sources/ContainerizationOCI/Version.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic struct RuntimeSpecVersion: Sendable {\n public let major, minor, patch: Int\n public let dev: String\n\n public static let current = RuntimeSpecVersion(\n major: 1,\n minor: 0,\n patch: 2,\n dev: \"-dev\"\n )\n\n public init(major: Int, minor: Int, patch: Int, dev: String) {\n self.major = major\n self.minor = minor\n self.patch = patch\n self.dev = dev\n }\n}\n"], ["/containerization/Sources/Containerization/Interface.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A network interface.\npublic protocol Interface: Sendable {\n /// The interface IPv4 address and subnet prefix length, as a CIDR address.\n /// Example: `192.168.64.3/24`\n var address: String { get }\n\n /// The IP address for the default route, or nil for no default route.\n var gateway: String? { get }\n\n /// The interface MAC address, or nil to auto-configure the address.\n var macAddress: String? { get }\n}\n"], ["/containerization/Sources/SendablePropertyMacros/SendablePropertyError.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Errors that can be thrown by `@SendableProperty`.\nenum SendablePropertyError: CustomStringConvertible, Error {\n case unexpectedError\n case onlyApplicableToVar\n case notApplicableToType\n\n var description: String {\n switch self {\n case .unexpectedError: return \"The macro encountered an unexpected error\"\n case .onlyApplicableToVar: return \"The macro can only be applied to a variable\"\n case .notApplicableToType: return \"The macro can't be applied to a variable of this type\"\n }\n }\n}\n"], ["/containerization/Sources/Containerization/VirtualMachineInstance.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// The runtime state of the virtual machine instance.\npublic enum VirtualMachineInstanceState: Sendable {\n case starting\n case running\n case stopped\n case stopping\n case unknown\n}\n\n/// A live instance of a virtual machine.\npublic protocol VirtualMachineInstance: Sendable {\n associatedtype Agent: VirtualMachineAgent\n\n // The state of the virtual machine.\n var state: VirtualMachineInstanceState { get }\n\n var mounts: [AttachedFilesystem] { get }\n /// Dial the Agent. It's up the VirtualMachineInstance to determine\n /// what port the agent is listening on.\n func dialAgent() async throws -> Agent\n /// Dial a vsock port in the guest.\n func dial(_ port: UInt32) async throws -> FileHandle\n /// Listen on a host vsock port.\n func listen(_ port: UInt32) throws -> VsockConnectionStream\n /// Stop listening on a vsock port.\n func stopListen(_ port: UInt32) throws\n /// Start the virtual machine.\n func start() async throws\n /// Stop the virtual machine.\n func stop() async throws\n}\n"], ["/containerization/Sources/Containerization/Image/Unpacker/Unpacker.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\n/// The `Unpacker` protocol defines a standardized interface that involves\n/// decompressing, extracting image layers and preparing it for use.\n///\n/// The `Unpacker` is responsible for managing the lifecycle of the\n/// unpacking process, including any temporary files or resources, until the\n/// `Mount` object is produced.\npublic protocol Unpacker {\n\n /// Unpacks the provided image to a specified path for a given platform.\n ///\n /// This asynchronous method should handle the entire unpacking process, from reading\n /// the `Image` layers for the given `Platform` via its `Manifest`,\n /// to making the extracted contents available as a `Mount`.\n /// Implementations of this method may apply platform-specific optimizations\n /// or transformations during the unpacking.\n ///\n /// Progress updates can be observed via the optional `progress` handler.\n func unpack(_ image: Image, for platform: Platform, at path: URL, progress: ProgressHandler?) async throws -> Mount\n\n}\n"], ["/containerization/Sources/ContainerizationEXT4/FileTimestamps.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct FileTimestamps {\n public var access: Date\n public var modification: Date\n public var creation: Date\n public var now: Date\n\n public var accessLo: UInt32 {\n access.fs().lo\n }\n\n public var accessHi: UInt32 {\n access.fs().hi\n }\n\n public var modificationLo: UInt32 {\n modification.fs().lo\n }\n\n public var modificationHi: UInt32 {\n modification.fs().hi\n }\n\n public var creationLo: UInt32 {\n creation.fs().lo\n }\n\n public var creationHi: UInt32 {\n creation.fs().hi\n }\n\n public var nowLo: UInt32 {\n now.fs().lo\n }\n\n public var nowHi: UInt32 {\n now.fs().hi\n }\n\n public init(access: Date?, modification: Date?, creation: Date?) {\n now = Date()\n self.access = access ?? now\n self.modification = modification ?? now\n self.creation = creation ?? now\n }\n\n public init() {\n self.init(access: nil, modification: nil, creation: nil)\n }\n}\n"], ["/containerization/Sources/SendableProperty/SendableProperty.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// A declaration of the `@SendableProperty` macro.\n@attached(peer, names: arbitrary)\n@attached(accessor)\npublic macro SendableProperty() = #externalMacro(module: \"SendablePropertyMacros\", type: \"SendablePropertyMacro\")\n"], ["/containerization/Sources/SendableProperty/SendablePropertyUnchecked.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// A declaration of the `@SendablePropertyUnchecked` macro.\n@attached(peer, names: arbitrary)\n@attached(accessor)\npublic macro SendablePropertyUnchecked() = #externalMacro(module: \"SendablePropertyMacros\", type: \"SendablePropertyMacroUnchecked\")\n"], ["/containerization/Sources/SendablePropertyMacros/SendablePropertyPlugin.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport SwiftCompilerPlugin\nimport SwiftSyntaxMacros\n\n/// A plugin that registers the `SendablePropertyMacroUnchecked` and `SendablePropertyMacro`.\n@main\nstruct SendablePropertyPlugin: CompilerPlugin {\n let providingMacros: [Macro.Type] = [\n SendablePropertyMacroUnchecked.self,\n SendablePropertyMacro.self,\n ]\n}\n"], ["/containerization/vminitd/Sources/vminitd/IOCloser+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\n\nextension Socket: IOCloser {}\n\nextension Terminal: IOCloser {\n var fileDescriptor: Int32 {\n self.handle.fileDescriptor\n }\n}\n\nextension FileHandle: IOCloser {}\n"], ["/containerization/Sources/Containerization/IO/ReaderStream.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A type that returns a stream of Data.\npublic protocol ReaderStream: Sendable {\n func stream() -> AsyncStream\n}\n"], ["/containerization/vminitd/Sources/vminitd/HostStdio.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nstruct HostStdio: Sendable {\n let stdin: UInt32?\n let stdout: UInt32?\n let stderr: UInt32?\n let terminal: Bool\n}\n"], ["/containerization/Sources/Containerization/VirtualMachineAgent+Additions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Protocol to conform to if your agent is capable of relaying unix domain socket\n/// connections.\npublic protocol SocketRelayAgent {\n func relaySocket(port: UInt32, configuration: UnixSocketConfiguration) async throws\n func stopSocketRelay(configuration: UnixSocketConfiguration) async throws\n}\n"], ["/containerization/vminitd/Sources/vminitd/IOCloser.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nprotocol IOCloser: Sendable {\n var fileDescriptor: Int32 { get }\n\n func close() throws\n}\n"], ["/containerization/Sources/Containerization/VirtualMachineManager.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A protocol to implement for virtual machine isolated containers.\npublic protocol VirtualMachineManager: Sendable {\n func create(container: Container) throws -> any VirtualMachineInstance\n}\n"], ["/containerization/Sources/Containerization/IO/Writer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A type that writes the provided Data.\npublic protocol Writer: Sendable {\n func write(_ data: Data) throws\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 03:23:08", "created_task_model": "DeepSeek-R1", "function_skeleton": "func run ( ) async throws { }", "code_description": "This code segment functions to: Initialize and manage container execution with specified resource allocations, configure shared file system access, establish network interfaces, handle terminal input/output interactions, and coordinate the complete lifecycle from creation to termination while maintaining runtime environment constraints."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```swift\n[TASK_BEGIN]\nfunc run() async throws {\n let mountPoints = try mounts.map { mountSpecifier in\n let parts = mountSpecifier.components(separatedBy: \":\")\n guard parts.count == 2 else {\n throw ValidationError(\"Invalid mount format: \\(mountSpecifier)\")\n }\n return MountPoint(source: URL(fileURLWithPath: parts[0]), destination: URL(fileURLWithPath: parts[1]))\n }\n\n var networkInterfaces: [NetworkInterface] = []\n if let ip = ip, let gateway = gateway {\n networkInterfaces.append(NetworkInterface(ipAddressWithSubnet: ip, gateway: gateway))\n }\n\n let config = ContainerConfiguration(\n id: id,\n imageReference: imageReference,\n command: arguments,\n cpus: UInt64(cpus),\n memory: memory * 1024 * 1024,\n blockFileSystemSize: fsSizeInMB * 1024 * 1024,\n mounts: mountPoints,\n networkInterfaces: networkInterfaces,\n nameservers: nameservers,\n kernel: URL(fileURLWithPath: kernel),\n workingDirectory: URL(fileURLWithPath: cwd)\n )\n\n let container = try Container(configuration: config, appRoot: Self.appRoot)\n try container.start()\n try await container.waitUntilFinished()\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 03-23-33"}, "editdistance_info": {"edit_distance": 10.6178, "calculate_time": "2025-08-21 03:23:33", "true_code_clean": "func run() async throws {\n let kernel = Kernel(\n path: URL(fileURLWithPath: kernel),\n platform: .linuxArm\n )\n let manager = try await ContainerManager(\n kernel: kernel,\n initfsReference: \"vminit:latest\",\n )\n let sigwinchStream = AsyncSignalHandler.create(notify: [SIGWINCH])\n let current = try Terminal.current\n try current.setraw()\n defer { current.tryReset() }\n let container = try await manager.create(\n id,\n reference: imageReference,\n rootfsSizeInBytes: fsSizeInMB.mib()\n ) { config in\n config.cpus = cpus\n config.memoryInBytes = memory.mib()\n config.process.setTerminalIO(terminal: current)\n config.process.arguments = arguments\n config.process.workingDirectory = cwd\n for mount in self.mounts {\n let paths = mount.split(separator: \":\")\n if paths.count != 2 {\n throw ContainerizationError(\n .invalidArgument,\n message: \"incorrect mount format detected: \\(mount)\"\n )\n }\n let host = String(paths[0])\n let guest = String(paths[1])\n let czMount = Containerization.Mount.share(\n source: host,\n destination: guest\n )\n config.mounts.append(czMount)\n }\n var hosts = Hosts.default\n if let ip {\n guard let gateway else {\n throw ContainerizationError(.invalidArgument, message: \"gateway must be specified\")\n }\n config.interfaces.append(NATInterface(address: ip, gateway: gateway))\n config.dns = .init(nameservers: [gateway])\n if nameservers.count > 0 {\n config.dns = .init(nameservers: nameservers)\n }\n hosts.entries.append(\n Hosts.Entry(\n ipAddress: ip,\n hostnames: [id]\n ))\n }\n config.hosts = hosts\n }\n defer {\n try? manager.delete(id)\n }\n try await container.create()\n try await container.start()\n try? await container.resize(to: try current.size)\n try await withThrowingTaskGroup(of: Void.self) { group in\n group.addTask {\n for await _ in sigwinchStream.signals {\n try await container.resize(to: try current.size)\n }\n }\n try await container.wait()\n group.cancelAll()\n try await container.stop()\n }\n }", "predict_code_clean": "func run() async throws {\n let mountPoints = try mounts.map { mountSpecifier in\n let parts = mountSpecifier.components(separatedBy: \":\")\n guard parts.count == 2 else {\n throw ValidationError(\"Invalid mount format: \\(mountSpecifier)\")\n }\n return MountPoint(source: URL(fileURLWithPath: parts[0]), destination: URL(fileURLWithPath: parts[1]))\n }\n var networkInterfaces: [NetworkInterface] = []\n if let ip = ip, let gateway = gateway {\n networkInterfaces.append(NetworkInterface(ipAddressWithSubnet: ip, gateway: gateway))\n }\n let config = ContainerConfiguration(\n id: id,\n imageReference: imageReference,\n command: arguments,\n cpus: UInt64(cpus),\n memory: memory * 1024 * 1024,\n blockFileSystemSize: fsSizeInMB * 1024 * 1024,\n mounts: mountPoints,\n networkInterfaces: networkInterfaces,\n nameservers: nameservers,\n kernel: URL(fileURLWithPath: kernel),\n workingDirectory: URL(fileURLWithPath: cwd)\n )\n let container = try Container(configuration: config, appRoot: Self.appRoot)\n try container.start()\n try await container.waitUntilFinished()\n}"}} +{"repo_name": "containerization", "file_name": "/containerization/Sources/Containerization/LinuxProcess.swift", "inference_info": {"prefix_code": "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport Synchronization\n\n/// `LinuxProcess` represents a Linux process and is used to\n/// setup and control the full lifecycle for the process.\npublic final class LinuxProcess: Sendable {\n /// The ID of the process. This is purely metadata for the caller.\n public let id: String\n\n /// What container owns this process (if any).\n public let owningContainer: String?\n\n package struct StdioSetup: Sendable {\n let port: UInt32\n let writer: Writer\n }\n\n package struct StdioReaderSetup {\n let port: UInt32\n let reader: ReaderStream\n }\n\n package struct Stdio: Sendable {\n let stdin: StdioReaderSetup?\n let stdout: StdioSetup?\n let stderr: StdioSetup?\n }\n\n private struct StdioHandles: Sendable {\n var stdin: FileHandle?\n var stdout: FileHandle?\n var stderr: FileHandle?\n\n mutating func close() throws {\n if let stdin {\n try stdin.close()\n stdin.readabilityHandler = nil\n self.stdin = nil\n }\n if let stdout {\n try stdout.close()\n stdout.readabilityHandler = nil\n self.stdout = nil\n }\n if let stderr {\n try stderr.close()\n stderr.readabilityHandler = nil\n self.stderr = nil\n }\n }\n }\n\n private struct State {\n var spec: ContainerizationOCI.Spec\n var pid: Int32\n var stdio: StdioHandles\n var stdinRelay: Task<(), Never>?\n var ioTracker: IoTracker?\n\n struct IoTracker {\n let stream: AsyncStream\n let cont: AsyncStream.Continuation\n let configuredStreams: Int\n }\n }\n\n /// The process ID for the container process. This will be -1\n /// if the process has not been started.\n public var pid: Int32 {\n state.withLock { $0.pid }\n }\n\n private let state: Mutex\n private let ioSetup: Stdio\n private let agent: any VirtualMachineAgent\n private let vm: any VirtualMachineInstance\n private let logger: Logger?\n\n init(\n _ id: String,\n containerID: String? = nil,\n spec: Spec,\n io: Stdio,\n agent: any VirtualMachineAgent,\n vm: any VirtualMachineInstance,\n logger: Logger?\n ) {\n self.id = id\n self.owningContainer = containerID\n self.state = Mutex(.init(spec: spec, pid: -1, stdio: StdioHandles()))\n self.ioSetup = io\n self.agent = agent\n self.vm = vm\n self.logger = logger\n }\n}\n\nextension LinuxProcess {\n func setupIO(streams: [VsockConnectionStream?]) async throws -> [FileHandle?] {\n let handles = try await Timeout.run(seconds: 3) {\n await withTaskGroup(of: (Int, FileHandle?).self) { group in\n var results = [FileHandle?](repeating: nil, count: 3)\n\n for (index, stream) in streams.enumerated() {\n guard let stream = stream else { continue }\n\n group.addTask {\n let first = await stream.connections.first(where: { _ in true })\n return (index, first)\n }\n }\n\n for await (index, fileHandle) in group {\n results[index] = fileHandle\n }\n return results\n }\n }\n\n if let stdin = self.ioSetup.stdin {\n if let handle = handles[0] {\n self.state.withLock {\n $0.stdinRelay = Task {\n for await data in stdin.reader.stream() {\n do {\n try handle.write(contentsOf: data)\n } catch {\n self.logger?.error(\"failed to write to stdin: \\(error)\")\n break\n }\n }\n\n do {\n self.logger?.debug(\"stdin relay finished, closing\")\n\n // There's two ways we can wind up here:\n //\n // 1. The stream finished on its own (e.g. we wrote all the\n // data) and we will close the underlying stdin in the guest below.\n //\n // 2. The client explicitly called closeStdin() themselves\n // which will cancel this relay task AFTER actually closing\n // the fds. If the client did that, then this task will be\n // cancelled, and the fds are already gone so there's nothing\n // for us to do.\n if Task.isCancelled {\n return\n }\n\n try await self._closeStdin()\n } catch {\n self.logger?.error(\"failed to close stdin: \\(error)\")\n }\n }\n }\n }\n }\n\n var configuredStreams = 0\n let (stream, cc) = AsyncStream.makeStream()\n if let stdout = self.ioSetup.stdout {\n configuredStreams += 1\n handles[1]?.readabilityHandler = { handle in\n do {\n let data = handle.availableData\n if data.isEmpty {\n // This block is called when the producer (the guest) closes\n // the fd it is writing into.\n handles[1]?.readabilityHandler = nil\n cc.yield()\n return\n }\n try stdout.writer.write(data)\n } catch {\n self.logger?.error(\"failed to write to stdout: \\(error)\")\n }\n }\n }\n\n if let stderr = self.ioSetup.stderr {\n configuredStreams += 1\n handles[2]?.readabilityHandler = { handle in\n do {\n let data = handle.availableData\n if data.isEmpty {\n handles[2]?.readabilityHandler = nil\n cc.yield()\n return\n }\n try stderr.writer.write(data)\n } catch {\n self.logger?.error(\"failed to write to stderr: \\(error)\")\n }\n }\n }\n if configuredStreams > 0 {\n self.state.withLock {\n $0.ioTracker = .init(stream: stream, cont: cc, configuredStreams: configuredStreams)\n }\n }\n\n return handles\n }\n\n /// Start the process.\n public func start() async throws {\n do {\n let spec = self.state.withLock { $0.spec }\n var streams = [VsockConnectionStream?](repeating: nil, count: 3)\n if let stdin = self.ioSetup.stdin {\n streams[0] = try self.vm.listen(stdin.port)\n }\n if let stdout = self.ioSetup.stdout {\n streams[1] = try self.vm.listen(stdout.port)\n }\n if let stderr = self.ioSetup.stderr {\n if spec.process!.terminal {\n throw ContainerizationError(\n .invalidArgument,\n message: \"stderr should not be configured with terminal=true\"\n )\n }\n streams[2] = try self.vm.listen(stderr.port)\n }\n\n let t = Task {\n try await self.setupIO(streams: streams)\n }\n\n try await agent.createProcess(\n id: self.id,\n containerID: self.owningContainer,\n stdinPort: self.ioSetup.stdin?.port,\n stdoutPort: self.ioSetup.stdout?.port,\n stderrPort: self.ioSetup.stderr?.port,\n configuration: spec,\n options: nil\n )\n\n let result = try await t.value\n let pid = try await self.agent.startProcess(\n id: self.id,\n containerID: self.owningContainer\n )\n\n self.state.withLock {\n $0.stdio = StdioHandles(\n stdin: result[0],\n stdout: result[1],\n stderr: result[2]\n )\n $0.pid = pid\n }\n } catch {\n if let err = error as? ContainerizationError {\n throw err\n }\n throw ContainerizationError(\n .internalError,\n message: \"failed to start process\",\n cause: error,\n )\n }\n }\n\n /// Kill the process with the specified signal.\n public func kill(_ signal: Int32) async throws {\n do {\n try await agent.signalProcess(\n id: self.id,\n containerID: self.owningContainer,\n signal: signal\n )\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to kill process\",\n cause: error\n )\n }\n }\n\n /// Resize the processes pty (if requested).\n public func resize(to: Terminal.Size) async throws {\n do {\n try await agent.resizeProcess(\n id: self.id,\n containerID: self.owningContainer,\n columns: UInt32(to.width),\n rows: UInt32(to.height)\n )\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to resize process\",\n cause: error\n )\n }\n }\n\n public func closeStdin() async throws {\n do {\n try await self._closeStdin()\n self.state.withLock {\n $0.stdinRelay?.cancel()\n }\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to close stdin\",\n cause: error,\n )\n }\n }\n\n func _closeStdin() async throws {\n try await self.agent.closeProcessStdin(\n id: self.id,\n containerID: self.owningContainer\n )\n }\n\n /// Wait on the process to exit with an optional timeout. Returns the exit code of the process.\n @discardableResult\n public func wait(timeoutInSeconds: Int64? = nil) async throws -> Int32 {\n do {\n let code = try await self.agent.waitProcess(\n id: self.id,\n containerID: self.owningContainer,\n timeoutInSeconds: timeoutInSeconds\n )\n await self.waitIoComplete()\n return code\n } catch {\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(\n .internalError,\n message: \"failed to wait on process\",\n cause: error\n )\n }\n }\n\n /// Wait until the standard output and standard error streams for the process have concluded.\n private func waitIoComplete() async {\n let ioTracker = self.state.withLock { $0.ioTracker }\n guard let ioTracker else {\n return\n }\n do {\n try await Timeout.run(seconds: 3) {\n var counter = ioTracker.configuredStreams\n for await _ in ioTracker.stream {\n counter -= 1\n if counter == 0 {\n ioTracker.cont.finish()\n break\n }\n }\n }\n } catch {\n self.logger?.error(\"Timeout waiting for IO to complete for process \\(id): \\(error)\")\n }\n self.state.withLock {\n $0.ioTracker = nil\n }\n }\n\n /// Cleans up guest state and waits on and closes any host resources (stdio handles).\n ", "suffix_code": "\n}\n", "middle_code": "public func delete() async throws {\n do {\n try await self.agent.deleteProcess(\n id: self.id,\n containerID: self.owningContainer\n )\n } catch {\n self.logger?.error(\n \"process deletion\",\n metadata: [\n \"id\": \"\\(self.id)\",\n \"error\": \"\\(error)\",\n ])\n }\n do {\n try self.state.withLock {\n $0.stdinRelay?.cancel()\n try $0.stdio.close()\n }\n } catch {\n self.logger?.error(\n \"closing process stdio\",\n metadata: [\n \"id\": \"\\(self.id)\",\n \"error\": \"\\(error)\",\n ])\n }\n do {\n try await self.agent.close()\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to close agent connection\",\n cause: error,\n )\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "swift", "sub_task_type": null}, "context_code": [["/containerization/Sources/Containerization/LinuxContainer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport Logging\nimport Synchronization\n\nimport struct ContainerizationOS.Terminal\n\n/// `LinuxContainer` is an easy to use type for launching and managing the\n/// full lifecycle of a Linux container ran inside of a virtual machine.\npublic final class LinuxContainer: Container, Sendable {\n /// The default PATH value for a process.\n public static let defaultPath = \"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\n\n /// The identifier of the container.\n public let id: String\n\n /// Rootfs for the container.\n public let rootfs: Mount\n\n /// Configuration for the container.\n public let config: Configuration\n\n /// The configuration for the LinuxContainer.\n public struct Configuration: Sendable {\n /// Configuration of a container process.\n public struct Process: Sendable {\n /// The arguments for the container process.\n public var arguments: [String] = []\n /// The environment variables for the container process.\n public var environmentVariables: [String] = [\"PATH=\\(LinuxContainer.defaultPath)\"]\n /// The working directory for the container process.\n public var workingDirectory: String = \"/\"\n /// The user the container process will run as.\n public var user: ContainerizationOCI.User = .init()\n /// The rlimits for the container process.\n public var rlimits: [POSIXRlimit] = []\n /// Whether to allocate a pseudo terminal for the process. If you'd like interactive\n /// behavior and are planning to use a terminal for stdin/out/err on the client side,\n /// this should likely be set to true.\n public var terminal: Bool = false\n /// The stdin for the process.\n public var stdin: ReaderStream?\n /// The stdout for the process.\n public var stdout: Writer?\n /// The stderr for the process.\n public var stderr: Writer?\n\n public init() {}\n\n public init(from config: ImageConfig) {\n self.workingDirectory = config.workingDir ?? \"/\"\n self.environmentVariables = config.env ?? []\n self.arguments = (config.entrypoint ?? []) + (config.cmd ?? [])\n self.user = {\n if let rawString = config.user {\n return User(username: rawString)\n }\n return User()\n }()\n }\n\n func toOCI() -> ContainerizationOCI.Process {\n ContainerizationOCI.Process(\n args: self.arguments,\n cwd: self.workingDirectory,\n env: self.environmentVariables,\n user: self.user,\n rlimits: self.rlimits,\n terminal: self.terminal\n )\n }\n\n /// Sets up IO to be handled by the passed in Terminal, and edits the\n /// process configuration to set the necessary state for using a pty.\n mutating public func setTerminalIO(terminal: Terminal) {\n self.environmentVariables.append(\"TERM=xterm\")\n self.terminal = true\n self.stdin = terminal\n self.stdout = terminal\n }\n }\n\n /// Configuration for the init process of the container.\n public var process = Process.init()\n /// The amount of cpus for the container.\n public var cpus: Int = 4\n /// The memory in bytes to give to the container.\n public var memoryInBytes: UInt64 = 1024.mib()\n /// The hostname for the container.\n public var hostname: String = \"\"\n /// The system control options for the container.\n public var sysctl: [String: String] = [:]\n /// The network interfaces for the container.\n public var interfaces: [any Interface] = []\n /// The Unix domain socket relays to setup for the container.\n public var sockets: [UnixSocketConfiguration] = []\n /// Whether rosetta x86-64 emulation should be setup for the container.\n public var rosetta: Bool = false\n /// Whether nested virtualization should be turned on for the container.\n public var virtualization: Bool = false\n /// The mounts for the container.\n public var mounts: [Mount] = LinuxContainer.defaultMounts()\n /// The DNS configuration for the container.\n public var dns: DNS?\n /// The hosts to add to /etc/hosts for the container.\n public var hosts: Hosts?\n\n public init() {}\n }\n\n /// `IOHandler` informs the container process about what should be done\n /// for the stdio streams.\n struct IOHandler: Sendable {\n public var stdin: ReaderStream?\n public var stdout: Writer?\n public var stderr: Writer?\n\n init(stdin: ReaderStream? = nil, stdout: Writer? = nil, stderr: Writer? = nil) {\n self.stdin = stdin\n self.stdout = stdout\n self.stderr = stderr\n }\n }\n\n private let state: Mutex\n\n // Ports to be allocated from for stdio and for\n // unix socket relays that are sharing a guest\n // uds to the host.\n private let hostVsockPorts: Atomic\n // Ports we request the guest to allocate for unix socket relays from\n // the host.\n private let guestVsockPorts: Atomic\n\n private enum State: Sendable {\n /// The container class has been created but no live resources are running.\n case initialized\n /// The container is creating and booting the underlying virtual resources.\n case creating(CreatingState)\n /// The container's virtual machine has been setup and the runtime environment has been configured.\n case created(CreatedState)\n /// The initial process of the container is preparing to start.\n case starting(StartingState)\n /// The initial process of the container has started and is running.\n case started(StartedState)\n /// The container is preparing to stop.\n case stopping(StoppingState)\n /// The container has run and fully stopped.\n case stopped\n /// An error occurred during the lifetime of this class.\n case errored(Swift.Error)\n\n struct CreatingState: Sendable {}\n\n struct CreatedState: Sendable {\n let vm: any VirtualMachineInstance\n let relayManager: UnixSocketRelayManager\n }\n\n struct StartingState: Sendable {\n let vm: any VirtualMachineInstance\n let relayManager: UnixSocketRelayManager\n\n init(_ state: CreatedState) {\n self.vm = state.vm\n self.relayManager = state.relayManager\n }\n }\n\n struct StartedState: Sendable {\n let vm: any VirtualMachineInstance\n let process: LinuxProcess\n let relayManager: UnixSocketRelayManager\n\n init(_ state: StartingState, process: LinuxProcess) {\n self.vm = state.vm\n self.relayManager = state.relayManager\n self.process = process\n }\n }\n\n struct StoppingState: Sendable {\n let vm: any VirtualMachineInstance\n\n init(_ state: StartedState) {\n self.vm = state.vm\n }\n }\n\n mutating func setCreating() throws {\n switch self {\n case .initialized:\n self = .creating(.init())\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in initialized state to start\"\n )\n }\n }\n\n mutating func setCreated(\n vm: any VirtualMachineInstance,\n relayManager: UnixSocketRelayManager\n ) throws {\n switch self {\n case .creating:\n self = .created(.init(vm: vm, relayManager: relayManager))\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in creating state before created\"\n )\n }\n }\n\n mutating func setStarting() throws -> any VirtualMachineInstance {\n switch self {\n case .created(let state):\n self = .starting(.init(state))\n return state.vm\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in created state before starting\"\n )\n }\n }\n\n mutating func setStarted(process: LinuxProcess) throws {\n switch self {\n case .starting(let state):\n self = .started(.init(state, process: process))\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in starting state before started\"\n )\n }\n }\n\n mutating func stopping() throws -> StartedState {\n switch self {\n case .started(let state):\n self = .stopping(.init(state))\n return state\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in a started state before stopping\"\n )\n }\n }\n\n func startedState(_ operation: String) throws -> StartedState {\n switch self {\n case .started(let state):\n return state\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"failed to \\(operation): container must be running\"\n )\n }\n }\n\n mutating func stopped() throws {\n switch self {\n case .stopping(_):\n self = .stopped\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in a stopping state before setting to stopped\"\n )\n }\n }\n\n mutating func errored(error: Swift.Error) {\n self = .errored(error)\n }\n }\n\n private let vmm: VirtualMachineManager\n private let logger: Logger?\n\n /// Create a new `LinuxContainer`. A `Mount` that contains the contents\n /// of the container image must be provided, as well as a `VirtualMachineManager`\n /// instance that will handle launching the virtual machine the container will\n /// execute inside of.\n public init(\n _ id: String,\n rootfs: Mount,\n vmm: VirtualMachineManager,\n logger: Logger? = nil,\n configuration: (inout Configuration) throws -> Void\n ) throws {\n self.id = id\n self.vmm = vmm\n self.hostVsockPorts = Atomic(0x1000_0000)\n self.guestVsockPorts = Atomic(0x1000_0000)\n self.rootfs = rootfs\n self.logger = logger\n\n var config = Configuration()\n try configuration(&config)\n\n self.config = config\n self.state = Mutex(.initialized)\n }\n\n private static func createDefaultRuntimeSpec(_ id: String) -> Spec {\n .init(\n process: .init(),\n hostname: id,\n root: .init(\n path: Self.guestRootfsPath(id),\n readonly: false\n ),\n linux: .init(\n resources: .init()\n )\n )\n }\n\n private func generateRuntimeSpec() -> Spec {\n var spec = Self.createDefaultRuntimeSpec(id)\n\n // Process toggles.\n spec.process = config.process.toOCI()\n\n // General toggles.\n spec.hostname = config.hostname\n\n // Linux toggles.\n var linux = ContainerizationOCI.Linux.init()\n linux.sysctl = config.sysctl\n spec.linux = linux\n\n return spec\n }\n\n public static func defaultMounts() -> [Mount] {\n let defaultOptions = [\"nosuid\", \"noexec\", \"nodev\"]\n return [\n .any(type: \"proc\", source: \"proc\", destination: \"/proc\", options: defaultOptions),\n .any(type: \"sysfs\", source: \"sysfs\", destination: \"/sys\", options: defaultOptions),\n .any(type: \"devtmpfs\", source: \"none\", destination: \"/dev\", options: [\"nosuid\", \"mode=755\"]),\n .any(type: \"mqueue\", source: \"mqueue\", destination: \"/dev/mqueue\", options: defaultOptions),\n .any(type: \"tmpfs\", source: \"tmpfs\", destination: \"/dev/shm\", options: defaultOptions + [\"mode=1777\", \"size=65536k\"]),\n .any(type: \"cgroup2\", source: \"none\", destination: \"/sys/fs/cgroup\", options: defaultOptions),\n .any(type: \"devpts\", source: \"devpts\", destination: \"/dev/pts\", options: [\"nosuid\", \"noexec\", \"gid=5\", \"mode=620\", \"ptmxmode=666\"]),\n ]\n }\n\n private static func guestRootfsPath(_ id: String) -> String {\n \"/run/container/\\(id)/rootfs\"\n }\n}\n\nextension LinuxContainer {\n package var root: String {\n Self.guestRootfsPath(id)\n }\n\n /// Number of CPU cores allocated.\n public var cpus: Int {\n config.cpus\n }\n\n /// Amount of memory in bytes allocated for the container.\n /// This will be aligned to a 1MB boundary if it isn't already.\n public var memoryInBytes: UInt64 {\n config.memoryInBytes\n }\n\n /// Network interfaces of the container.\n public var interfaces: [any Interface] {\n config.interfaces\n }\n\n /// Create the underlying container's virtual machine\n /// and set up the runtime environment.\n public func create() async throws {\n try self.state.withLock { try $0.setCreating() }\n\n let vm = try vmm.create(container: self)\n try await vm.start()\n do {\n try await vm.withAgent { agent in\n let relayManager = UnixSocketRelayManager(vm: vm)\n\n try await agent.standardSetup()\n\n // Mount the rootfs.\n var rootfs = vm.mounts[0].to\n rootfs.destination = Self.guestRootfsPath(self.id)\n try await agent.mount(rootfs)\n\n // Start up our friendly unix socket relays.\n for socket in self.config.sockets {\n try await self.relayUnixSocket(\n socket: socket,\n relayManager: relayManager,\n agent: agent\n )\n }\n\n // For every interface asked for:\n // 1. Add the address requested\n // 2. Online the adapter\n // 3. If a gateway IP address is present, add the default route.\n for (index, i) in self.interfaces.enumerated() {\n let name = \"eth\\(index)\"\n try await agent.addressAdd(name: name, address: i.address)\n try await agent.up(name: name, mtu: 1280)\n if let gateway = i.gateway {\n try await agent.routeAddDefault(name: name, gateway: gateway)\n }\n }\n\n // Setup /etc/resolv.conf and /etc/hosts if asked for.\n if let dns = self.config.dns {\n try await agent.configureDNS(config: dns, location: rootfs.destination)\n }\n if let hosts = self.config.hosts {\n try await agent.configureHosts(config: hosts, location: rootfs.destination)\n }\n\n try self.state.withLock { try $0.setCreated(vm: vm, relayManager: relayManager) }\n }\n } catch {\n try? await vm.stop()\n self.state.withLock { $0.errored(error: error) }\n throw error\n }\n }\n\n /// Start the container container's initial process.\n public func start() async throws {\n let vm = try self.state.withLock { try $0.setStarting() }\n\n let agent = try await vm.dialAgent()\n do {\n var spec = generateRuntimeSpec()\n // We don't need the rootfs, nor do OCI runtimes want it included.\n spec.mounts = vm.mounts.dropFirst().map { $0.to }\n\n let stdio = Self.setupIO(\n portAllocator: self.hostVsockPorts,\n stdin: self.config.process.stdin,\n stdout: self.config.process.stdout,\n stderr: self.config.process.stderr\n )\n\n let process = LinuxProcess(\n self.id,\n containerID: self.id,\n spec: spec,\n io: stdio,\n agent: agent,\n vm: vm,\n logger: self.logger\n )\n try await process.start()\n\n try self.state.withLock { try $0.setStarted(process: process) }\n } catch {\n try? await agent.close()\n self.state.withLock { $0.errored(error: error) }\n throw error\n }\n }\n\n private static func setupIO(\n portAllocator: borrowing Atomic,\n stdin: ReaderStream?,\n stdout: Writer?,\n stderr: Writer?\n ) -> LinuxProcess.Stdio {\n var stdinSetup: LinuxProcess.StdioReaderSetup? = nil\n if let reader = stdin {\n let ret = portAllocator.wrappingAdd(1, ordering: .relaxed)\n stdinSetup = .init(\n port: ret.oldValue,\n reader: reader\n )\n }\n\n var stdoutSetup: LinuxProcess.StdioSetup? = nil\n if let writer = stdout {\n let ret = portAllocator.wrappingAdd(1, ordering: .relaxed)\n stdoutSetup = LinuxProcess.StdioSetup(\n port: ret.oldValue,\n writer: writer\n )\n }\n\n var stderrSetup: LinuxProcess.StdioSetup? = nil\n if let writer = stderr {\n let ret = portAllocator.wrappingAdd(1, ordering: .relaxed)\n stderrSetup = LinuxProcess.StdioSetup(\n port: ret.oldValue,\n writer: writer\n )\n }\n\n return LinuxProcess.Stdio(\n stdin: stdinSetup,\n stdout: stdoutSetup,\n stderr: stderrSetup\n )\n }\n\n /// Stop the container from executing.\n public func stop() async throws {\n let startedState = try self.state.withLock { try $0.stopping() }\n\n try await startedState.relayManager.stopAll()\n\n // It's possible the state of the vm is not in a great spot\n // if the guest panicked or had any sort of bug/fault.\n // First check if the vm is even still running, as trying to\n // use a vsock handle like below here will cause NIO to\n // fatalError because we'll get an EBADF.\n if startedState.vm.state == .stopped {\n try self.state.withLock { try $0.stopped() }\n return\n }\n\n try await startedState.vm.withAgent { agent in\n // First, we need to stop any unix socket relays as this will\n // keep the rootfs from being able to umount (EBUSY).\n let sockets = config.sockets\n if !sockets.isEmpty {\n guard let relayAgent = agent as? SocketRelayAgent else {\n throw ContainerizationError(\n .unsupported,\n message: \"VirtualMachineAgent does not support relaySocket surface\"\n )\n }\n for socket in sockets {\n try await relayAgent.stopSocketRelay(configuration: socket)\n }\n }\n\n // Now lets ensure every process is donezo.\n try await agent.kill(pid: -1, signal: SIGKILL)\n\n // Wait on init proc exit. Give it 5 seconds of leeway.\n _ = try await agent.waitProcess(\n id: self.id,\n containerID: self.id,\n timeoutInSeconds: 5\n )\n\n // Today, we leave EBUSY looping and other fun logic up to the\n // guest agent.\n try await agent.umount(\n path: Self.guestRootfsPath(self.id),\n flags: 0\n )\n }\n\n // Lets free up the init procs resources, as this includes the open agent conn.\n try? await startedState.process.delete()\n\n try await startedState.vm.stop()\n try self.state.withLock { try $0.stopped() }\n }\n\n /// Send a signal to the container.\n public func kill(_ signal: Int32) async throws {\n let state = try self.state.withLock { try $0.startedState(\"kill\") }\n try await state.process.kill(signal)\n }\n\n /// Wait for the container to exit. Returns the exit code.\n @discardableResult\n public func wait(timeoutInSeconds: Int64? = nil) async throws -> Int32 {\n let state = try self.state.withLock { try $0.startedState(\"wait\") }\n return try await state.process.wait(timeoutInSeconds: timeoutInSeconds)\n }\n\n /// Resize the container's terminal (if one was requested). This\n /// will error if terminal was set to false before creating the container.\n public func resize(to: Terminal.Size) async throws {\n let state = try self.state.withLock { try $0.startedState(\"resize\") }\n try await state.process.resize(to: to)\n }\n\n /// Execute a new process in the container.\n public func exec(_ id: String, configuration: (inout Configuration.Process) throws -> Void) async throws -> LinuxProcess {\n let state = try self.state.withLock { try $0.startedState(\"exec\") }\n\n var spec = generateRuntimeSpec()\n var config = Configuration.Process()\n try configuration(&config)\n spec.process = config.toOCI()\n\n let stdio = Self.setupIO(\n portAllocator: self.hostVsockPorts,\n stdin: config.stdin,\n stdout: config.stdout,\n stderr: config.stderr\n )\n let agent = try await state.vm.dialAgent()\n let process = LinuxProcess(\n id,\n containerID: self.id,\n spec: spec,\n io: stdio,\n agent: agent,\n vm: state.vm,\n logger: self.logger\n )\n return process\n }\n\n /// Execute a new process in the container.\n public func exec(_ id: String, configuration: Configuration.Process) async throws -> LinuxProcess {\n let state = try self.state.withLock { try $0.startedState(\"exec\") }\n\n var spec = generateRuntimeSpec()\n spec.process = configuration.toOCI()\n\n let stdio = Self.setupIO(\n portAllocator: self.hostVsockPorts,\n stdin: configuration.stdin,\n stdout: configuration.stdout,\n stderr: configuration.stderr\n )\n let agent = try await state.vm.dialAgent()\n let process = LinuxProcess(\n id,\n containerID: self.id,\n spec: spec,\n io: stdio,\n agent: agent,\n vm: state.vm,\n logger: self.logger\n )\n return process\n }\n\n /// Dial a vsock port in the container.\n public func dialVsock(port: UInt32) async throws -> FileHandle {\n let state = try self.state.withLock { try $0.startedState(\"dialVsock\") }\n return try await state.vm.dial(port)\n }\n\n /// Close the containers standard input to signal no more input is\n /// arriving.\n public func closeStdin() async throws {\n let state = try self.state.withLock { try $0.startedState(\"closeStdin\") }\n return try await state.process.closeStdin()\n }\n\n /// Relay a unix socket from in the container to the host, or from the host\n /// to inside the container.\n public func relayUnixSocket(socket: UnixSocketConfiguration) async throws {\n let state = try self.state.withLock { try $0.startedState(\"relayUnixSocket\") }\n\n try await state.vm.withAgent { agent in\n try await self.relayUnixSocket(\n socket: socket,\n relayManager: state.relayManager,\n agent: agent\n )\n }\n }\n\n private func relayUnixSocket(\n socket: UnixSocketConfiguration,\n relayManager: UnixSocketRelayManager,\n agent: any VirtualMachineAgent\n ) async throws {\n guard let relayAgent = agent as? SocketRelayAgent else {\n throw ContainerizationError(\n .unsupported,\n message: \"VirtualMachineAgent does not support relaySocket surface\"\n )\n }\n\n var socket = socket\n let rootInGuest = URL(filePath: self.root)\n\n if socket.direction == .into {\n socket.destination = rootInGuest.appending(path: socket.destination.path)\n } else {\n socket.source = rootInGuest.appending(path: socket.source.path)\n }\n\n let port = self.hostVsockPorts.wrappingAdd(1, ordering: .relaxed).oldValue\n try await relayManager.start(port: port, socket: socket)\n try await relayAgent.relaySocket(port: port, configuration: socket)\n }\n}\n\nextension VirtualMachineInstance {\n /// Scoped access to an agent instance to ensure the resources are always freed (mostly close(2)'ing\n /// the vsock fd)\n fileprivate func withAgent(fn: @Sendable (VirtualMachineAgent) async throws -> Void) async throws {\n let agent = try await self.dialAgent()\n do {\n try await fn(agent)\n try await agent.close()\n } catch {\n try? await agent.close()\n throw error\n }\n }\n}\n\nextension AttachedFilesystem {\n fileprivate var to: ContainerizationOCI.Mount {\n .init(\n type: self.type,\n source: self.source,\n destination: self.destination,\n options: self.options\n )\n }\n}\n\n#endif\n"], ["/containerization/Sources/Containerization/UnixSocketRelay.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationIO\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport Synchronization\n\npackage actor UnixSocketRelayManager {\n private let vm: any VirtualMachineInstance\n private var relays: [String: SocketRelay]\n private let q: DispatchQueue\n private let log: Logger?\n\n init(vm: any VirtualMachineInstance, log: Logger? = nil) {\n self.vm = vm\n self.relays = [:]\n self.q = DispatchQueue(label: \"com.apple.containerization.socket-relay\")\n self.log = log\n }\n}\n\nextension UnixSocketRelayManager {\n func start(port: UInt32, socket: UnixSocketConfiguration) async throws {\n guard self.relays[socket.id] == nil else {\n throw ContainerizationError(\n .invalidState,\n message: \"socket relay \\(socket.id) already started\"\n )\n }\n\n let socketRelay = try SocketRelay(\n port: port,\n socket: socket,\n vm: self.vm,\n queue: self.q,\n log: self.log\n )\n\n do {\n self.relays[socket.id] = socketRelay\n try await socketRelay.start()\n } catch {\n self.relays.removeValue(forKey: socket.id)\n }\n }\n\n func stop(socket: UnixSocketConfiguration) async throws {\n guard let storedRelay = self.relays.removeValue(forKey: socket.id) else {\n throw ContainerizationError(\n .notFound,\n message: \"failed to stop socket relay\"\n )\n }\n try storedRelay.stop()\n }\n\n func stopAll() async throws {\n for (_, relay) in self.relays {\n try relay.stop()\n }\n }\n}\n\npackage final class SocketRelay: Sendable {\n private let port: UInt32\n private let configuration: UnixSocketConfiguration\n private let log: Logger?\n private let vm: any VirtualMachineInstance\n private let q: DispatchQueue\n private let state: Mutex\n\n private struct State {\n var relaySources: [String: ConnectionSources] = [:]\n var t: Task<(), Never>? = nil\n }\n\n // `DispatchSourceRead` is thread-safe.\n private struct ConnectionSources: @unchecked Sendable {\n let hostSource: DispatchSourceRead\n let guestSource: DispatchSourceRead\n }\n\n init(\n port: UInt32,\n socket: UnixSocketConfiguration,\n vm: any VirtualMachineInstance,\n queue: DispatchQueue,\n log: Logger? = nil\n ) throws {\n self.port = port\n self.configuration = socket\n self.state = Mutex(.init())\n self.vm = vm\n self.log = log\n self.q = queue\n }\n\n deinit {\n self.state.withLock { $0.t?.cancel() }\n }\n}\n\nextension SocketRelay {\n func start() async throws {\n switch configuration.direction {\n case .outOf:\n try await setupHostVsockDial()\n case .into:\n try setupHostVsockListener()\n }\n }\n\n func stop() throws {\n try self.state.withLock {\n guard let t = $0.t else {\n throw ContainerizationError(\n .invalidState,\n message: \"failed to stop socket relay: relay has not been started\"\n )\n }\n t.cancel()\n $0.t = nil\n $0.relaySources.removeAll()\n }\n\n switch configuration.direction {\n case .outOf:\n // If we created the host conn, lets unlink it also. It's possible it was\n // already unlinked if the relay failed earlier.\n try? FileManager.default.removeItem(at: self.configuration.destination)\n case .into:\n try self.vm.stopListen(self.port)\n }\n }\n\n private func setupHostVsockDial() async throws {\n let hostConn = self.configuration.destination\n\n let socketType = try UnixType(\n path: hostConn.path,\n unlinkExisting: true\n )\n let hostSocket = try Socket(type: socketType)\n try hostSocket.listen()\n\n let connectionStream = try hostSocket.acceptStream(closeOnDeinit: false)\n self.state.withLock {\n $0.t = Task {\n do {\n for try await connection in connectionStream {\n try await self.handleHostUnixConn(\n hostConn: connection,\n port: self.port,\n vm: self.vm,\n log: self.log\n )\n }\n } catch {\n log?.error(\"failed in unix socket relay loop: \\(error)\")\n }\n try? FileManager.default.removeItem(at: hostConn)\n }\n }\n }\n\n private func setupHostVsockListener() throws {\n let hostPath = self.configuration.source\n let port = self.port\n let log = self.log\n\n let connectionStream = try self.vm.listen(self.port)\n self.state.withLock {\n $0.t = Task {\n do {\n defer { connectionStream.finish() }\n for await connection in connectionStream.connections {\n try await self.handleGuestVsockConn(\n vsockConn: connection,\n hostConnectionPath: hostPath,\n port: port,\n log: log\n )\n }\n } catch {\n log?.error(\"failed to setup relay between vsock \\(port) and \\(hostPath.path): \\(error)\")\n }\n }\n }\n }\n\n private func handleHostUnixConn(\n hostConn: ContainerizationOS.Socket,\n port: UInt32,\n vm: any VirtualMachineInstance,\n log: Logger?\n ) async throws {\n do {\n let guestConn = try await vm.dial(port)\n try await self.relay(\n hostConn: hostConn,\n guestFd: guestConn.fileDescriptor\n )\n } catch {\n log?.error(\"failed to relay between vsock \\(port) and \\(hostConn)\")\n throw error\n }\n }\n\n private func handleGuestVsockConn(\n vsockConn: FileHandle,\n hostConnectionPath: URL,\n port: UInt32,\n log: Logger?\n ) async throws {\n let hostPath = hostConnectionPath.path\n let socketType = try UnixType(path: hostPath)\n let hostSocket = try Socket(\n type: socketType,\n closeOnDeinit: false\n )\n try hostSocket.connect()\n\n do {\n try await self.relay(\n hostConn: hostSocket,\n guestFd: vsockConn.fileDescriptor\n )\n } catch {\n log?.error(\"failed to relay between vsock \\(port) and \\(hostPath)\")\n }\n }\n\n private func relay(\n hostConn: Socket,\n guestFd: Int32\n ) async throws {\n let connSource = DispatchSource.makeReadSource(\n fileDescriptor: hostConn.fileDescriptor,\n queue: self.q\n )\n let vsockConnectionSource = DispatchSource.makeReadSource(\n fileDescriptor: guestFd,\n queue: self.q\n )\n\n let pairID = UUID().uuidString\n self.state.withLock {\n $0.relaySources[pairID] = ConnectionSources(\n hostSource: connSource,\n guestSource: vsockConnectionSource\n )\n }\n\n nonisolated(unsafe) let buf1 = UnsafeMutableBufferPointer.allocate(capacity: Int(getpagesize()))\n connSource.setEventHandler {\n Self.fdCopyHandler(\n buffer: buf1,\n source: connSource,\n from: hostConn.fileDescriptor,\n to: guestFd\n )\n }\n\n nonisolated(unsafe) let buf2 = UnsafeMutableBufferPointer.allocate(capacity: Int(getpagesize()))\n vsockConnectionSource.setEventHandler {\n Self.fdCopyHandler(\n buffer: buf2,\n source: vsockConnectionSource,\n from: guestFd,\n to: hostConn.fileDescriptor\n )\n }\n\n connSource.setCancelHandler {\n if !connSource.isCancelled {\n connSource.cancel()\n }\n if !vsockConnectionSource.isCancelled {\n vsockConnectionSource.cancel()\n }\n try? hostConn.close()\n }\n\n vsockConnectionSource.setCancelHandler {\n if !vsockConnectionSource.isCancelled {\n vsockConnectionSource.cancel()\n }\n if !connSource.isCancelled {\n connSource.cancel()\n }\n close(guestFd)\n }\n\n connSource.activate()\n vsockConnectionSource.activate()\n }\n\n private static func fdCopyHandler(\n buffer: UnsafeMutableBufferPointer,\n source: DispatchSourceRead,\n from sourceFd: Int32,\n to destinationFd: Int32,\n log: Logger? = nil\n ) {\n if source.data == 0 {\n if !source.isCancelled {\n source.cancel()\n }\n return\n }\n\n do {\n try self.fileDescriptorCopy(\n buffer: buffer,\n size: source.data,\n from: sourceFd,\n to: destinationFd\n )\n } catch {\n log?.error(\"file descriptor copy failed \\(error)\")\n if !source.isCancelled {\n source.cancel()\n }\n }\n }\n\n private static func fileDescriptorCopy(\n buffer: UnsafeMutableBufferPointer,\n size: UInt,\n from sourceFd: Int32,\n to destinationFd: Int32\n ) throws {\n let bufferSize = buffer.count\n var readBytesRemaining = min(Int(size), bufferSize)\n\n guard let baseAddr = buffer.baseAddress else {\n throw ContainerizationError(\n .invalidState,\n message: \"buffer has no base address\"\n )\n }\n\n while readBytesRemaining > 0 {\n let readResult = read(sourceFd, baseAddr, min(bufferSize, readBytesRemaining))\n if readResult <= 0 {\n throw ContainerizationError(\n .internalError,\n message: \"missing pointer base address\"\n )\n }\n readBytesRemaining -= readResult\n\n var writeBytesRemaining = readResult\n while writeBytesRemaining > 0 {\n let writeResult = write(destinationFd, baseAddr, writeBytesRemaining)\n if writeResult <= 0 {\n throw ContainerizationError(\n .internalError,\n message: \"zero byte write or error in socket relay\"\n )\n }\n writeBytesRemaining -= writeResult\n }\n }\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/Server+GRPC.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport ContainerizationNetlink\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport GRPC\nimport Logging\nimport NIOCore\nimport NIOPosix\nimport _NIOFileSystem\n\nprivate let _setenv = Foundation.setenv\n\n#if canImport(Musl)\nimport Musl\nprivate let _mount = Musl.mount\nprivate let _umount = Musl.umount2\nprivate let _kill = Musl.kill\nprivate let _sync = Musl.sync\n#elseif canImport(Glibc)\nimport Glibc\nprivate let _mount = Glibc.mount\nprivate let _umount = Glibc.umount2\nprivate let _kill = Glibc.kill\nprivate let _sync = Glibc.sync\n#endif\n\nextension Initd: Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncProvider {\n func setTime(\n request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetTimeResponse {\n log.debug(\n \"setTime\",\n metadata: [\n \"sec\": \"\\(request.sec)\",\n \"usec\": \"\\(request.usec)\",\n ])\n\n var tv = timeval(tv_sec: time_t(request.sec), tv_usec: suseconds_t(request.usec))\n guard settimeofday(&tv, nil) == 0 else {\n let error = swiftErrno(\"settimeofday\")\n log.error(\n \"setTime\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"failed to settimeofday: \\(error)\")\n }\n\n return .init()\n }\n\n func setupEmulator(\n request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse {\n log.debug(\n \"setupEmulator\",\n metadata: [\n \"request\": \"\\(request)\"\n ])\n\n if !Binfmt.mounted() {\n throw GRPCStatus(\n code: .internalError,\n message: \"\\(Binfmt.path) is not mounted\"\n )\n }\n\n do {\n let bfmt = Binfmt.Entry(\n name: request.name,\n type: request.type,\n offset: request.offset,\n magic: request.magic,\n mask: request.mask,\n flags: request.flags\n )\n try bfmt.register(binaryPath: request.binaryPath)\n } catch {\n log.error(\n \"setupEmulator\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"setupEmulator: failed to register binfmt_misc entry: \\(error)\"\n )\n }\n\n return .init()\n }\n\n func sysctl(\n request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SysctlResponse {\n log.debug(\n \"sysctl\",\n metadata: [\n \"settings\": \"\\(request.settings)\"\n ])\n\n do {\n let sysctlPath = URL(fileURLWithPath: \"/proc/sys/\")\n for (k, v) in request.settings {\n guard let data = v.data(using: .ascii) else {\n throw GRPCStatus(code: .internalError, message: \"failed to convert \\(v) to data buffer for sysctl write\")\n }\n\n let setting =\n sysctlPath\n .appendingPathComponent(k.replacingOccurrences(of: \".\", with: \"/\"))\n let fh = try FileHandle(forWritingTo: setting)\n defer { try? fh.close() }\n\n try fh.write(contentsOf: data)\n }\n } catch {\n log.error(\n \"sysctl\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"sysctl: failed to set sysctl: \\(error)\"\n )\n }\n\n return .init()\n }\n\n func proxyVsock(\n request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse {\n log.debug(\n \"proxyVsock\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"port\": \"\\(request.vsockPort)\",\n \"guestPath\": \"\\(request.guestPath)\",\n \"action\": \"\\(request.action)\",\n ])\n\n do {\n let proxy = VsockProxy(\n id: request.id,\n action: request.action == .into ? .dial : .listen,\n port: request.vsockPort,\n path: URL(fileURLWithPath: request.guestPath),\n udsPerms: request.guestSocketPermissions,\n log: log\n )\n\n try proxy.start()\n try await state.add(proxy: proxy)\n } catch {\n log.error(\n \"proxyVsock\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"proxyVsock: failed to setup vsock proxy: \\(error)\"\n )\n }\n\n return .init()\n }\n\n func stopVsockProxy(\n request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse {\n log.debug(\n \"stopVsockProxy\",\n metadata: [\n \"id\": \"\\(request.id)\"\n ])\n\n do {\n let proxy = try await state.remove(proxy: request.id)\n try proxy.close()\n } catch {\n log.error(\n \"stopVsockProxy\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"stopVsockProxy: failed to stop vsock proxy: \\(error)\"\n )\n }\n\n return .init()\n }\n\n func mkdir(request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest, context: GRPC.GRPCAsyncServerCallContext)\n async throws -> Com_Apple_Containerization_Sandbox_V3_MkdirResponse\n {\n log.debug(\n \"mkdir\",\n metadata: [\n \"path\": \"\\(request.path)\",\n \"all\": \"\\(request.all)\",\n ])\n\n do {\n try FileManager.default.createDirectory(\n atPath: request.path,\n withIntermediateDirectories: request.all\n )\n } catch {\n log.error(\n \"mkdir\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"mkdir: \\(error)\")\n }\n\n return .init()\n }\n\n func mount(request: Com_Apple_Containerization_Sandbox_V3_MountRequest, context: GRPC.GRPCAsyncServerCallContext)\n async throws -> Com_Apple_Containerization_Sandbox_V3_MountResponse\n {\n log.debug(\n \"mount\",\n metadata: [\n \"type\": \"\\(request.type)\",\n \"source\": \"\\(request.source)\",\n \"destination\": \"\\(request.destination)\",\n ])\n\n do {\n let mnt = ContainerizationOS.Mount(\n type: request.type,\n source: request.source,\n target: request.destination,\n options: request.options\n )\n\n #if os(Linux)\n try mnt.mount(createWithPerms: 0o755)\n return .init()\n #else\n fatalError(\"mount not supported on platform\")\n #endif\n } catch {\n log.error(\n \"mount\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"mount: \\(error)\")\n }\n }\n\n func umount(request: Com_Apple_Containerization_Sandbox_V3_UmountRequest, context: GRPC.GRPCAsyncServerCallContext)\n async throws -> Com_Apple_Containerization_Sandbox_V3_UmountResponse\n {\n log.debug(\n \"umount\",\n metadata: [\n \"path\": \"\\(request.path)\",\n \"flags\": \"\\(request.flags)\",\n ])\n\n #if os(Linux)\n // Best effort EBUSY handle.\n for _ in 0...50 {\n let result = _umount(request.path, request.flags)\n if result == -1 {\n if errno == EBUSY {\n try await Task.sleep(for: .milliseconds(10))\n continue\n }\n let error = swiftErrno(\"umount\")\n\n log.error(\n \"umount\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .invalidArgument, message: \"umount: \\(error)\")\n }\n break\n }\n return .init()\n #else\n fatalError(\"umount not supported on platform\")\n #endif\n }\n\n func setenv(request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest, context: GRPC.GRPCAsyncServerCallContext)\n async throws -> Com_Apple_Containerization_Sandbox_V3_SetenvResponse\n {\n log.debug(\n \"setenv\",\n metadata: [\n \"key\": \"\\(request.key)\",\n \"value\": \"\\(request.value)\",\n ])\n\n guard _setenv(request.key, request.value, 1) == 0 else {\n let error = swiftErrno(\"setenv\")\n\n log.error(\n \"setEnv\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n\n throw GRPCStatus(code: .invalidArgument, message: \"setenv: \\(error)\")\n }\n return .init()\n }\n\n func getenv(request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest, context: GRPC.GRPCAsyncServerCallContext)\n async throws -> Com_Apple_Containerization_Sandbox_V3_GetenvResponse\n {\n log.debug(\n \"getenv\",\n metadata: [\n \"key\": \"\\(request.key)\"\n ])\n\n let env = ProcessInfo.processInfo.environment[request.key]\n return .with {\n if let env {\n $0.value = env\n }\n }\n }\n\n func createProcess(\n request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest, context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse {\n log.debug(\n \"createProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"stdin\": \"Port: \\(request.stdin)\",\n \"stdout\": \"Port: \\(request.stdout)\",\n \"stderr\": \"Port: \\(request.stderr)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n do {\n var ociSpec = try JSONDecoder().decode(\n ContainerizationOCI.Spec.self,\n from: request.configuration\n )\n\n try ociAlterations(ociSpec: &ociSpec)\n\n guard let process = ociSpec.process else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"oci runtime spec missing process configuration\"\n )\n }\n\n let stdioPorts = HostStdio(\n stdin: request.hasStdin ? request.stdin : nil,\n stdout: request.hasStdout ? request.stdout : nil,\n stderr: request.hasStderr ? request.stderr : nil,\n terminal: process.terminal\n )\n\n // This is an exec.\n if let container = await self.state.containers[request.containerID] {\n try await container.createExec(\n id: request.id,\n stdio: stdioPorts,\n process: process\n )\n } else {\n // We need to make our new fangled container.\n // The process ID must match the container ID for this.\n guard request.id == request.containerID else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"init process id must match container id\"\n )\n }\n\n // Write the etc/hostname file in the container rootfs since some init-systems\n // depend on it.\n let hostname = ociSpec.hostname\n if let root = ociSpec.root, !hostname.isEmpty {\n let etc = URL(fileURLWithPath: root.path).appendingPathComponent(\"etc\")\n try FileManager.default.createDirectory(atPath: etc.path, withIntermediateDirectories: true)\n let hostnamePath = etc.appendingPathComponent(\"hostname\")\n try hostname.write(toFile: hostnamePath.path, atomically: true, encoding: .utf8)\n }\n\n let ctr = try ManagedContainer(\n id: request.id,\n stdio: stdioPorts,\n spec: ociSpec,\n log: self.log\n )\n try await self.state.add(container: ctr)\n }\n\n return .init()\n } catch {\n log.error(\n \"createProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"error\": \"\\(error)\",\n ])\n if error is GRPCStatus {\n throw error\n }\n throw GRPCStatus(code: .internalError, message: \"create managed process: \\(error)\")\n }\n }\n\n func killProcess(\n request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillProcessResponse {\n log.debug(\n \"killProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"signal\": \"\\(request.signal)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n let ctr = try await self.state.get(container: request.containerID)\n try await ctr.kill(execID: request.id, request.signal)\n\n return .init()\n }\n\n func deleteProcess(\n request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest, context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse {\n log.debug(\n \"deleteProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n let ctr = try await self.state.get(container: request.containerID)\n\n // Are we trying to delete the container itself?\n if request.id == request.containerID {\n try await ctr.delete()\n try await state.remove(container: request.id)\n } else {\n // Or just a single exec.\n try await ctr.deleteExec(id: request.id)\n }\n\n return .init()\n }\n\n func startProcess(\n request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest, context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StartProcessResponse {\n log.debug(\n \"startProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n do {\n let ctr = try await self.state.get(container: request.containerID)\n let pid = try await ctr.start(execID: request.id)\n\n return .with {\n $0.pid = pid\n }\n } catch {\n log.error(\n \"startProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"error\": \"\\(error)\",\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"startProcess: failed to start process: \\(error)\"\n )\n }\n }\n\n func resizeProcess(\n request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest, context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse {\n log.debug(\n \"resizeProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n do {\n let ctr = try await self.state.get(container: request.containerID)\n let size = Terminal.Size(\n width: UInt16(request.columns),\n height: UInt16(request.rows)\n )\n try await ctr.resize(execID: request.id, size: size)\n } catch {\n log.error(\n \"resizeProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"error\": \"\\(error)\",\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"resizeProcess: failed to resize process: \\(error)\"\n )\n }\n\n return .init()\n }\n\n func waitProcess(\n request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest, context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse {\n log.debug(\n \"waitProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n do {\n let ctr = try await self.state.get(container: request.containerID)\n\n let exitCode = try await ctr.wait(execID: request.id)\n\n return .with {\n $0.exitCode = exitCode\n }\n } catch {\n log.error(\n \"waitProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"error\": \"\\(error)\",\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"waitProcess: failed to wait on process: \\(error)\"\n )\n }\n }\n\n func closeProcessStdin(\n request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest, context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse {\n log.debug(\n \"closeProcessStdin\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n do {\n let ctr = try await self.state.get(container: request.containerID)\n\n try await ctr.closeStdin(execID: request.id)\n\n return .init()\n } catch {\n log.error(\n \"closeProcessStdin\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"error\": \"\\(error)\",\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"closeProcessStdin: failed to close process stdin: \\(error)\"\n )\n }\n }\n\n func ipLinkSet(\n request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest, context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse {\n log.debug(\n \"ip-link-set\",\n metadata: [\n \"interface\": \"\\(request.interface)\",\n \"up\": \"\\(request.up)\",\n ])\n\n do {\n let socket = try DefaultNetlinkSocket()\n let session = NetlinkSession(socket: socket, log: log)\n let mtuValue: UInt32? = request.hasMtu ? request.mtu : nil\n try session.linkSet(interface: request.interface, up: request.up, mtu: mtuValue)\n } catch {\n log.error(\n \"ip-link-set\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"ip-link-set: \\(error)\")\n }\n\n return .init()\n }\n\n func ipAddrAdd(\n request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest, context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse {\n log.debug(\n \"ip-addr-add\",\n metadata: [\n \"interface\": \"\\(request.interface)\",\n \"addr\": \"\\(request.address)\",\n ])\n\n do {\n let socket = try DefaultNetlinkSocket()\n let session = NetlinkSession(socket: socket, log: log)\n try session.addressAdd(interface: request.interface, address: request.address)\n } catch {\n log.error(\n \"ip-addr-add\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"ip-addr-add: \\(error)\")\n }\n\n return .init()\n }\n\n func ipRouteAddLink(\n request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest, context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse {\n log.debug(\n \"ip-route-add-link\",\n metadata: [\n \"interface\": \"\\(request.interface)\",\n \"address\": \"\\(request.address)\",\n \"srcAddr\": \"\\(request.srcAddr)\",\n ])\n\n do {\n let socket = try DefaultNetlinkSocket()\n let session = NetlinkSession(socket: socket, log: log)\n try session.routeAdd(\n interface: request.interface,\n destinationAddress: request.address,\n srcAddr: request.srcAddr\n )\n } catch {\n log.error(\n \"ip-route-add-link\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"ip-route-add-link: \\(error)\")\n }\n\n return .init()\n }\n\n func ipRouteAddDefault(\n request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse {\n log.debug(\n \"ip-route-add-default\",\n metadata: [\n \"interface\": \"\\(request.interface)\",\n \"gateway\": \"\\(request.gateway)\",\n ])\n\n do {\n let socket = try DefaultNetlinkSocket()\n let session = NetlinkSession(socket: socket, log: log)\n try session.routeAddDefault(interface: request.interface, gateway: request.gateway)\n } catch {\n log.error(\n \"ip-route-add-default\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"ip-route-add-default: \\(error)\")\n }\n\n return .init()\n }\n\n func configureDns(\n request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse {\n let domain = request.hasDomain ? request.domain : nil\n log.debug(\n \"configure-dns\",\n metadata: [\n \"location\": \"\\(request.location)\",\n \"nameservers\": \"\\(request.nameservers)\",\n \"domain\": \"\\(domain ?? \"\")\",\n ])\n\n do {\n let etc = URL(fileURLWithPath: request.location).appendingPathComponent(\"etc\")\n try FileManager.default.createDirectory(atPath: etc.path, withIntermediateDirectories: true)\n let resolvConf = etc.appendingPathComponent(\"resolv.conf\")\n let config = DNS(\n nameservers: request.nameservers,\n domain: domain,\n searchDomains: request.searchDomains,\n options: request.options\n )\n let text = config.resolvConf\n log.debug(\"writing to path \\(resolvConf.path) \\(text)\")\n try text.write(toFile: resolvConf.path, atomically: true, encoding: .utf8)\n log.debug(\"wrote resolver configuration\", metadata: [\"path\": \"\\(resolvConf.path)\"])\n } catch {\n log.error(\n \"configure-dns\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"configure-dns: \\(error)\")\n }\n\n return .init()\n }\n\n func configureHosts(\n request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse {\n log.debug(\n \"configureHosts\",\n metadata: [\n \"location\": \"\\(request.location)\"\n ])\n\n do {\n let etc = URL(fileURLWithPath: request.location).appendingPathComponent(\"etc\")\n try FileManager.default.createDirectory(atPath: etc.path, withIntermediateDirectories: true)\n let hostsPath = etc.appendingPathComponent(\"hosts\")\n\n let config = request.toCZHosts()\n let text = config.hostsFile\n try text.write(toFile: hostsPath.path, atomically: true, encoding: .utf8)\n\n log.debug(\"wrote /etc/hosts configuration\", metadata: [\"path\": \"\\(hostsPath.path)\"])\n } catch {\n log.error(\n \"configureHosts\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"configureHosts: \\(error)\")\n }\n\n return .init()\n }\n\n private func swiftErrno(_ msg: Logger.Message) -> POSIXError {\n let error = POSIXError(.init(rawValue: errno)!)\n log.error(\n msg,\n metadata: [\n \"error\": \"\\(error)\"\n ])\n return error\n }\n\n func sync(\n request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SyncResponse {\n log.debug(\"sync\")\n\n _sync()\n return .init()\n }\n\n func kill(\n request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillResponse {\n log.debug(\n \"kill\",\n metadata: [\n \"pid\": \"\\(request.pid)\",\n \"signal\": \"\\(request.signal)\",\n ])\n\n let r = _kill(request.pid, request.signal)\n return .with {\n $0.result = r\n }\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest {\n func toCZHosts() -> Hosts {\n let entries = self.entries.map {\n Hosts.Entry(\n ipAddress: $0.ipAddress,\n hostnames: $0.hostnames,\n comment: $0.hasComment ? $0.comment : nil\n )\n }\n return Hosts(\n entries: entries,\n comment: self.hasComment ? self.comment : nil\n )\n }\n}\n\nextension Initd {\n func ociAlterations(ociSpec: inout ContainerizationOCI.Spec) throws {\n guard var process = ociSpec.process else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"runtime spec without process field present\"\n )\n }\n guard let root = ociSpec.root else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"runtime spec without root field present\"\n )\n }\n\n if process.cwd.isEmpty {\n process.cwd = \"/\"\n }\n\n // Username is truthfully a Windows field, but we use this as away to pass through\n // the exact string representation of a username a client may have given us.\n let username = process.user.username.isEmpty ? \"\\(process.user.uid):\\(process.user.gid)\" : process.user.username\n let parsedUser = try User.parseUser(root: root.path, userString: username)\n process.user.uid = parsedUser.uid\n process.user.gid = parsedUser.gid\n process.user.additionalGids = parsedUser.sgids\n if !process.env.contains(where: { $0.hasPrefix(\"HOME=\") }) {\n process.env.append(\"HOME=\\(parsedUser.home)\")\n }\n\n // Defensive programming a tad, but ensure we have TERM set if\n // the client requested a pty.\n if process.terminal {\n let termEnv = \"TERM=\"\n if !process.env.contains(where: { $0.hasPrefix(termEnv) }) {\n process.env.append(\"TERM=xterm\")\n }\n }\n\n ociSpec.process = process\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/ManagedProcess.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport GRPC\nimport Logging\nimport Synchronization\n\nfinal class ManagedProcess: Sendable {\n let id: String\n\n private let log: Logger\n private let process: Command\n private let lock: Mutex\n private let syncfd: Pipe\n private let owningPid: Int32?\n\n private struct State {\n init(io: IO) {\n self.io = io\n }\n\n let io: IO\n var waiters: [CheckedContinuation] = []\n var exitStatus: Int32? = nil\n var pid: Int32 = 0\n }\n\n var pid: Int32 {\n self.lock.withLock {\n $0.pid\n }\n }\n\n // swiftlint: disable type_name\n protocol IO {\n func start(process: inout Command) throws\n func closeAfterExec() throws\n func resize(size: Terminal.Size) throws\n func closeStdin() throws\n }\n // swiftlint: enable type_name\n\n static func localizeLogger(log: inout Logger, id: String) {\n log[metadataKey: \"id\"] = \"\\(id)\"\n }\n\n init(\n id: String,\n stdio: HostStdio,\n bundle: ContainerizationOCI.Bundle,\n owningPid: Int32? = nil,\n log: Logger\n ) throws {\n self.id = id\n var log = log\n Self.localizeLogger(log: &log, id: id)\n self.log = log\n self.owningPid = owningPid\n\n let syncfd = Pipe()\n try syncfd.setCloexec()\n self.syncfd = syncfd\n\n let args: [String]\n if let owningPid {\n args = [\n \"exec\",\n \"--parent-pid\",\n \"\\(owningPid)\",\n \"--process-path\",\n bundle.getExecSpecPath(id: id).path,\n ]\n } else {\n args = [\"run\", \"--bundle-path\", bundle.path.path]\n }\n\n var process = Command(\n \"/sbin/vmexec\",\n arguments: args,\n extraFiles: [syncfd.fileHandleForWriting]\n )\n\n var io: IO\n if stdio.terminal {\n log.info(\"setting up terminal IO\")\n let attrs = Command.Attrs(setsid: false, setctty: false)\n process.attrs = attrs\n io = try TerminalIO(\n stdio: stdio,\n log: log\n )\n } else {\n process.attrs = .init(setsid: false)\n io = StandardIO(\n stdio: stdio,\n log: log\n )\n }\n\n log.info(\"starting io\")\n\n // Setup IO early. We expect the host to be listening already.\n try io.start(process: &process)\n\n self.process = process\n self.lock = Mutex(State(io: io))\n }\n}\n\nextension ManagedProcess {\n func start() throws -> Int32 {\n try self.lock.withLock {\n log.info(\n \"starting managed process\",\n metadata: [\n \"id\": \"\\(id)\"\n ])\n\n // Start the underlying process.\n try process.start()\n\n // Close our side of any pipes.\n try syncfd.fileHandleForWriting.close()\n try $0.io.closeAfterExec()\n\n guard let piddata = try syncfd.fileHandleForReading.readToEnd() else {\n throw ContainerizationError(.internalError, message: \"no pid data from sync pipe\")\n }\n\n let i = piddata.withUnsafeBytes { ptr in\n ptr.load(as: Int32.self)\n }\n\n log.info(\"got back pid data \\(i)\")\n $0.pid = i\n\n log.info(\n \"started managed process\",\n metadata: [\n \"pid\": \"\\(i)\",\n \"id\": \"\\(id)\",\n ])\n\n return i\n }\n }\n\n func setExit(_ status: Int32) {\n self.lock.withLock {\n self.log.info(\n \"managed process exit\",\n metadata: [\n \"status\": \"\\(status)\"\n ])\n\n $0.exitStatus = status\n\n for waiter in $0.waiters {\n waiter.resume(returning: status)\n }\n\n self.log.debug(\"\\($0.waiters.count) managed process waiters signaled\")\n $0.waiters.removeAll()\n }\n }\n\n /// Wait on the process to exit\n func wait() async -> Int32 {\n await withCheckedContinuation { cont in\n self.lock.withLock {\n if let status = $0.exitStatus {\n cont.resume(returning: status)\n return\n }\n $0.waiters.append(cont)\n }\n }\n }\n\n func kill(_ signal: Int32) throws {\n try self.lock.withLock {\n guard $0.exitStatus == nil else {\n return\n }\n\n self.log.info(\"sending signal \\(signal) to process \\($0.pid)\")\n guard Foundation.kill($0.pid, signal) == 0 else {\n throw POSIXError.fromErrno()\n }\n }\n }\n\n func resize(size: Terminal.Size) throws {\n try self.lock.withLock {\n guard $0.exitStatus == nil else {\n return\n }\n try $0.io.resize(size: size)\n }\n }\n\n func closeStdin() throws {\n try self.lock.withLock {\n try $0.io.closeStdin()\n }\n }\n}\n"], ["/containerization/Sources/Containerization/Agent/Vminitd.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport GRPC\nimport NIOPosix\n\n/// A remote connection into the vminitd Linux guest agent via a port (vsock).\n/// Used to modify the runtime environment of the Linux sandbox.\npublic struct Vminitd: Sendable {\n public typealias Client = Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClient\n\n // Default vsock port that the agent and client use.\n public static let port: UInt32 = 1024\n\n private static let defaultPath = \"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\n\n let client: Client\n\n public init(client: Client) {\n self.client = client\n }\n\n public init(connection: FileHandle, group: MultiThreadedEventLoopGroup) {\n self.client = .init(connection: connection, group: group)\n }\n\n /// Close the connection to the guest agent.\n public func close() async throws {\n try await client.close()\n }\n}\n\nextension Vminitd: VirtualMachineAgent {\n /// Perform the standard guest setup necessary for vminitd to be able to\n /// run containers.\n public func standardSetup() async throws {\n try await up(name: \"lo\")\n\n try await setenv(key: \"PATH\", value: Self.defaultPath)\n\n let mounts: [ContainerizationOCI.Mount] = [\n // NOTE: /proc is always done implicitly by the guest agent.\n .init(type: \"tmpfs\", source: \"tmpfs\", destination: \"/run\"),\n .init(type: \"sysfs\", source: \"sysfs\", destination: \"/sys\"),\n .init(type: \"tmpfs\", source: \"tmpfs\", destination: \"/tmp\"),\n .init(type: \"devpts\", source: \"devpts\", destination: \"/dev/pts\", options: [\"gid=5\", \"mode=620\", \"ptmxmode=666\"]),\n .init(type: \"cgroup2\", source: \"none\", destination: \"/sys/fs/cgroup\"),\n ]\n for mount in mounts {\n try await self.mount(mount)\n }\n }\n\n /// Mount a filesystem in the sandbox's environment.\n public func mount(_ mount: ContainerizationOCI.Mount) async throws {\n _ = try await client.mount(\n .with {\n $0.type = mount.type\n $0.source = mount.source\n $0.destination = mount.destination\n $0.options = mount.options\n })\n }\n\n /// Unmount a filesystem in the sandbox's environment.\n public func umount(path: String, flags: Int32) async throws {\n _ = try await client.umount(\n .with {\n $0.path = path\n $0.flags = flags\n })\n }\n\n /// Create a directory inside the sandbox's environment.\n public func mkdir(path: String, all: Bool, perms: UInt32) async throws {\n _ = try await client.mkdir(\n .with {\n $0.path = path\n $0.all = all\n $0.perms = perms\n })\n }\n\n public func createProcess(\n id: String,\n containerID: String?,\n stdinPort: UInt32?,\n stdoutPort: UInt32?,\n stderrPort: UInt32?,\n configuration: ContainerizationOCI.Spec,\n options: Data?\n ) async throws {\n let enc = JSONEncoder()\n _ = try await client.createProcess(\n .with {\n $0.id = id\n if let stdinPort {\n $0.stdin = stdinPort\n }\n if let stdoutPort {\n $0.stdout = stdoutPort\n }\n if let stderrPort {\n $0.stderr = stderrPort\n }\n if let containerID {\n $0.containerID = containerID\n }\n $0.configuration = try enc.encode(configuration)\n })\n }\n\n @discardableResult\n public func startProcess(id: String, containerID: String?) async throws -> Int32 {\n let request = Com_Apple_Containerization_Sandbox_V3_StartProcessRequest.with {\n $0.id = id\n if let containerID {\n $0.containerID = containerID\n }\n }\n let resp = try await client.startProcess(request)\n return resp.pid\n }\n\n public func signalProcess(id: String, containerID: String?, signal: Int32) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_KillProcessRequest.with {\n $0.id = id\n $0.signal = signal\n if let containerID {\n $0.containerID = containerID\n }\n }\n _ = try await client.killProcess(request)\n }\n\n public func resizeProcess(id: String, containerID: String?, columns: UInt32, rows: UInt32) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest.with {\n if let containerID {\n $0.containerID = containerID\n }\n $0.id = id\n $0.columns = columns\n $0.rows = rows\n }\n _ = try await client.resizeProcess(request)\n }\n\n public func waitProcess(id: String, containerID: String?, timeoutInSeconds: Int64? = nil) async throws -> Int32 {\n let request = Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest.with {\n $0.id = id\n if let containerID {\n $0.containerID = containerID\n }\n }\n var callOpts: CallOptions?\n if let timeoutInSeconds {\n var copts = CallOptions()\n copts.timeLimit = .timeout(.seconds(timeoutInSeconds))\n callOpts = copts\n }\n do {\n let resp = try await client.waitProcess(request, callOptions: callOpts)\n return resp.exitCode\n } catch {\n if let err = error as? GRPCError.RPCTimedOut {\n throw ContainerizationError(\n .timeout,\n message: \"failed to wait for process exit within timeout of \\(timeoutInSeconds!) seconds\",\n cause: err\n )\n }\n throw error\n }\n }\n\n public func deleteProcess(id: String, containerID: String?) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest.with {\n $0.id = id\n if let containerID {\n $0.containerID = containerID\n }\n }\n _ = try await client.deleteProcess(request)\n }\n\n public func closeProcessStdin(id: String, containerID: String?) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest.with {\n $0.id = id\n if let containerID {\n $0.containerID = containerID\n }\n }\n _ = try await client.closeProcessStdin(request)\n }\n\n public func up(name: String, mtu: UInt32? = nil) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest.with {\n $0.interface = name\n $0.up = true\n if let mtu { $0.mtu = mtu }\n }\n _ = try await client.ipLinkSet(request)\n }\n\n public func down(name: String) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest.with {\n $0.interface = name\n $0.up = false\n }\n _ = try await client.ipLinkSet(request)\n }\n\n /// Get an environment variable from the sandbox's environment.\n public func getenv(key: String) async throws -> String {\n let response = try await client.getenv(\n .with {\n $0.key = key\n })\n return response.value\n }\n\n /// Set an environment variable in the sandbox's environment.\n public func setenv(key: String, value: String) async throws {\n _ = try await client.setenv(\n .with {\n $0.key = key\n $0.value = value\n })\n }\n}\n\n/// Vminitd specific rpcs.\nextension Vminitd {\n /// Sets up an emulator in the guest.\n public func setupEmulator(binaryPath: String, configuration: Binfmt.Entry) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest.with {\n $0.binaryPath = binaryPath\n $0.name = configuration.name\n $0.type = configuration.type\n $0.offset = configuration.offset\n $0.magic = configuration.magic\n $0.mask = configuration.mask\n $0.flags = configuration.flags\n }\n _ = try await client.setupEmulator(request)\n }\n\n /// Sets the guest time.\n public func setTime(sec: Int64, usec: Int32) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_SetTimeRequest.with {\n $0.sec = sec\n $0.usec = usec\n }\n _ = try await client.setTime(request)\n }\n\n /// Set the provided sysctls inside the Sandbox's environment.\n public func sysctl(settings: [String: String]) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_SysctlRequest.with {\n $0.settings = settings\n }\n _ = try await client.sysctl(request)\n }\n\n /// Add an IP address to the sandbox's network interfaces.\n public func addressAdd(name: String, address: String) async throws {\n _ = try await client.ipAddrAdd(\n .with {\n $0.interface = name\n $0.address = address\n })\n }\n\n /// Set the default route in the sandbox's environment.\n public func routeAddDefault(name: String, gateway: String) async throws {\n _ = try await client.ipRouteAddDefault(\n .with {\n $0.interface = name\n $0.gateway = gateway\n })\n }\n\n /// Configure DNS within the sandbox's environment.\n public func configureDNS(config: DNS, location: String) async throws {\n _ = try await client.configureDns(\n .with {\n $0.location = location\n $0.nameservers = config.nameservers\n if let domain = config.domain {\n $0.domain = domain\n }\n $0.searchDomains = config.searchDomains\n $0.options = config.options\n })\n }\n\n /// Configure /etc/hosts within the sandbox's environment.\n public func configureHosts(config: Hosts, location: String) async throws {\n _ = try await client.configureHosts(config.toAgentHostsRequest(location: location))\n }\n\n /// Perform a sync call.\n public func sync() async throws {\n _ = try await client.sync(.init())\n }\n\n public func kill(pid: Int32, signal: Int32) async throws -> Int32 {\n let response = try await client.kill(\n .with {\n $0.pid = pid\n $0.signal = signal\n })\n return response.result\n }\n\n /// Syncing shutdown will send a SIGTERM to all processes\n /// and wait, perform a sync operation, then issue a SIGKILL\n /// to the remaining processes before syncing again.\n public func syncingShutdown() async throws {\n _ = try await self.kill(pid: -1, signal: SIGTERM)\n try await Task.sleep(for: .milliseconds(10))\n try await self.sync()\n\n _ = try await self.kill(pid: -1, signal: SIGKILL)\n try await Task.sleep(for: .milliseconds(10))\n try await self.sync()\n }\n}\n\nextension Hosts {\n func toAgentHostsRequest(location: String) -> Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest {\n Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.with {\n $0.location = location\n if let comment {\n $0.comment = comment\n }\n $0.entries = entries.map {\n let entry = $0\n return Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.HostsEntry.with {\n if let comment = entry.comment {\n $0.comment = comment\n }\n $0.ipAddress = entry.ipAddress\n $0.hostnames = entry.hostnames\n }\n }\n }\n }\n}\n\nextension Vminitd.Client {\n public init(socket: String, group: MultiThreadedEventLoopGroup) {\n var config = ClientConnection.Configuration.default(\n target: .unixDomainSocket(socket),\n eventLoopGroup: group\n )\n config.maximumReceiveMessageLength = Int(64.mib())\n config.connectionBackoff = ConnectionBackoff(retries: .upTo(5))\n\n self = .init(channel: ClientConnection(configuration: config))\n }\n\n public init(connection: FileHandle, group: MultiThreadedEventLoopGroup) {\n var config = ClientConnection.Configuration.default(\n target: .connectedSocket(connection.fileDescriptor),\n eventLoopGroup: group\n )\n config.maximumReceiveMessageLength = Int(64.mib())\n config.connectionBackoff = ConnectionBackoff(retries: .upTo(5))\n\n self = .init(channel: ClientConnection(configuration: config))\n }\n\n public func close() async throws {\n try await self.channel.close().get()\n }\n}\n"], ["/containerization/Sources/Containerization/VZVirtualMachineInstance.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Logging\nimport NIOCore\nimport NIOPosix\nimport Synchronization\nimport Virtualization\n\nstruct VZVirtualMachineInstance: VirtualMachineInstance, Sendable {\n typealias Agent = Vminitd\n\n /// Attached mounts on the sandbox.\n public let mounts: [AttachedFilesystem]\n\n /// Returns the runtime state of the vm.\n public var state: VirtualMachineInstanceState {\n vzStateToInstanceState()\n }\n\n /// The sandbox configuration.\n private let config: Configuration\n public struct Configuration: Sendable {\n /// Amount of cpus to allocated.\n public var cpus: Int\n /// Amount of memory in bytes allocated.\n public var memoryInBytes: UInt64\n /// Toggle rosetta's x86_64 emulation support.\n public var rosetta: Bool\n /// Toggle nested virtualization support.\n public var nestedVirtualization: Bool\n /// Mount attachments.\n public var mounts: [Mount]\n /// Network interface attachments.\n public var interfaces: [any Interface]\n /// Kernel image.\n public var kernel: Kernel?\n /// The root filesystem.\n public var initialFilesystem: Mount?\n /// File path to store the sandbox boot logs.\n public var bootlog: URL?\n\n init() {\n self.cpus = 4\n self.memoryInBytes = 1024.mib()\n self.rosetta = false\n self.nestedVirtualization = false\n self.mounts = []\n self.interfaces = []\n }\n }\n\n private nonisolated(unsafe) let vm: VZVirtualMachine\n private let queue: DispatchQueue\n private let group: MultiThreadedEventLoopGroup\n private let lock: AsyncLock\n private let timeSyncer: TimeSyncer\n private let logger: Logger?\n\n public init(\n group: MultiThreadedEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount),\n logger: Logger? = nil,\n with: (inout Configuration) throws -> Void\n ) throws {\n var config = Configuration()\n try with(&config)\n try self.init(group: group, config: config, logger: logger)\n }\n\n init(group: MultiThreadedEventLoopGroup, config: Configuration, logger: Logger?) throws {\n self.config = config\n self.group = group\n self.lock = .init()\n self.queue = DispatchQueue(label: \"com.apple.containerization.sandbox.\\(UUID().uuidString)\")\n self.mounts = try config.mountAttachments()\n self.logger = logger\n self.timeSyncer = .init(logger: logger)\n\n self.vm = VZVirtualMachine(\n configuration: try config.toVZ(),\n queue: self.queue\n )\n }\n}\n\nextension VZVirtualMachineInstance {\n func vzStateToInstanceState() -> VirtualMachineInstanceState {\n self.queue.sync {\n let state: VirtualMachineInstanceState\n switch self.vm.state {\n case .starting:\n state = .starting\n case .running:\n state = .running\n case .stopping:\n state = .stopping\n case .stopped:\n state = .stopped\n default:\n state = .unknown\n }\n return state\n }\n }\n\n func start() async throws {\n try await lock.withLock { _ in\n guard self.state == .stopped else {\n throw ContainerizationError(\n .invalidState,\n message: \"sandbox is not stopped \\(self.state)\"\n )\n }\n\n // Do any necessary setup needed prior to starting the guest.\n try await self.prestart()\n\n try await self.vm.start(queue: self.queue)\n\n let agent = Vminitd(\n connection: try await self.vm.waitForAgent(queue: self.queue),\n group: self.group\n )\n\n do {\n if self.config.rosetta {\n try await agent.enableRosetta()\n }\n } catch {\n try await agent.close()\n throw error\n }\n\n // Don't close our remote context as we are providing\n // it to our time sync routine.\n await self.timeSyncer.start(context: agent)\n }\n }\n\n func stop() async throws {\n try await lock.withLock { _ in\n // NOTE: We should record HOW the vm stopped eventually. If the vm exited\n // unexpectedly virtualization framework offers you a way to store\n // an error on how it exited. We should report that here instead of the\n // generic vm is not running.\n guard self.state == .running else {\n throw ContainerizationError(.invalidState, message: \"vm is not running\")\n }\n\n try await self.timeSyncer.close()\n\n try await self.vm.stop(queue: self.queue)\n try await self.group.shutdownGracefully()\n }\n }\n\n public func dialAgent() async throws -> Vminitd {\n let conn = try await dial(Vminitd.port)\n return Vminitd(connection: conn, group: self.group)\n }\n}\n\nextension VZVirtualMachineInstance {\n func dial(_ port: UInt32) async throws -> FileHandle {\n try await vm.connect(\n queue: queue,\n port: port\n ).dupHandle()\n }\n\n func listen(_ port: UInt32) throws -> VsockConnectionStream {\n let stream = VsockConnectionStream(port: port)\n let listener = VZVirtioSocketListener()\n listener.delegate = stream\n\n try self.vm.listen(\n queue: queue,\n port: port,\n listener: listener\n )\n return stream\n }\n\n func stopListen(_ port: UInt32) throws {\n try self.vm.removeListener(\n queue: queue,\n port: port\n )\n }\n\n func prestart() async throws {\n if self.config.rosetta {\n #if arch(arm64)\n if VZLinuxRosettaDirectoryShare.availability == .notInstalled {\n self.logger?.info(\"installing rosetta\")\n try await VZVirtualMachineInstance.Configuration.installRosetta()\n }\n #else\n fatalError(\"rosetta is only supported on arm64\")\n #endif\n }\n }\n}\n\nextension VZVirtualMachineInstance.Configuration {\n public static func installRosetta() async throws {\n do {\n #if arch(arm64)\n try await VZLinuxRosettaDirectoryShare.installRosetta()\n #else\n fatalError(\"rosetta is only supported on arm64\")\n #endif\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to install rosetta\",\n cause: error\n )\n }\n }\n\n private func serialPort(path: URL) throws -> [VZVirtioConsoleDeviceSerialPortConfiguration] {\n let c = VZVirtioConsoleDeviceSerialPortConfiguration()\n c.attachment = try VZFileSerialPortAttachment(url: path, append: true)\n return [c]\n }\n\n func toVZ() throws -> VZVirtualMachineConfiguration {\n var config = VZVirtualMachineConfiguration()\n\n config.cpuCount = self.cpus\n config.memorySize = self.memoryInBytes\n config.entropyDevices = [VZVirtioEntropyDeviceConfiguration()]\n config.socketDevices = [VZVirtioSocketDeviceConfiguration()]\n if let bootlog = self.bootlog {\n config.serialPorts = try serialPort(path: bootlog)\n }\n\n config.networkDevices = try self.interfaces.map {\n guard let vzi = $0 as? VZInterface else {\n throw ContainerizationError(.invalidArgument, message: \"interface type not supported by VZ\")\n }\n return try vzi.device()\n }\n\n if self.rosetta {\n #if arch(arm64)\n switch VZLinuxRosettaDirectoryShare.availability {\n case .notSupported:\n throw ContainerizationError(\n .invalidArgument,\n message: \"rosetta was requested but is not supported on this machine\"\n )\n case .notInstalled:\n // NOTE: If rosetta isn't installed, we'll error with a nice error message\n // during .start() of the virtual machine instance.\n fallthrough\n case .installed:\n let share = try VZLinuxRosettaDirectoryShare()\n let device = VZVirtioFileSystemDeviceConfiguration(tag: \"rosetta\")\n device.share = share\n config.directorySharingDevices.append(device)\n @unknown default:\n throw ContainerizationError(\n .invalidArgument,\n message: \"unknown rosetta availability encountered: \\(VZLinuxRosettaDirectoryShare.availability)\"\n )\n }\n #else\n fatalError(\"rosetta is only supported on arm64\")\n #endif\n }\n\n guard let kernel = self.kernel else {\n throw ContainerizationError(.invalidArgument, message: \"kernel cannot be nil\")\n }\n\n guard let initialFilesystem = self.initialFilesystem else {\n throw ContainerizationError(.invalidArgument, message: \"rootfs cannot be nil\")\n }\n\n let loader = VZLinuxBootLoader(kernelURL: kernel.path)\n loader.commandLine = kernel.linuxCommandline(initialFilesystem: initialFilesystem)\n config.bootLoader = loader\n\n try initialFilesystem.configure(config: &config)\n for mount in self.mounts {\n try mount.configure(config: &config)\n }\n\n let platform = VZGenericPlatformConfiguration()\n // We shouldn't silently succeed if the user asked for virt and their hardware does\n // not support it.\n if !VZGenericPlatformConfiguration.isNestedVirtualizationSupported && self.nestedVirtualization {\n throw ContainerizationError(\n .unsupported,\n message: \"nested virtualization is not supported on the platform\"\n )\n }\n platform.isNestedVirtualizationEnabled = self.nestedVirtualization\n config.platform = platform\n\n try config.validate()\n return config\n }\n\n func mountAttachments() throws -> [AttachedFilesystem] {\n let allocator = Character.blockDeviceTagAllocator()\n if let initialFilesystem {\n // When the initial filesystem is a blk, allocate the first letter \"vd(a)\"\n // as that is what this blk will be attached under.\n if initialFilesystem.isBlock {\n _ = try allocator.allocate()\n }\n }\n\n var attachments: [AttachedFilesystem] = []\n for mount in self.mounts {\n attachments.append(try .init(mount: mount, allocator: allocator))\n }\n return attachments\n }\n}\n\nextension Mount {\n var isBlock: Bool {\n type == \"ext4\"\n }\n}\n\nextension Kernel {\n func linuxCommandline(initialFilesystem: Mount) -> String {\n var args = self.commandLine.kernelArgs\n\n args.append(\"init=/sbin/vminitd\")\n // rootfs is always set as ro.\n args.append(\"ro\")\n\n switch initialFilesystem.type {\n case \"virtiofs\":\n args.append(contentsOf: [\n \"rootfstype=virtiofs\",\n \"root=rootfs\",\n ])\n case \"ext4\":\n args.append(contentsOf: [\n \"rootfstype=ext4\",\n \"root=/dev/vda\",\n ])\n default:\n fatalError(\"unsupported initfs filesystem \\(initialFilesystem.type)\")\n }\n\n if self.commandLine.initArgs.count > 0 {\n args.append(\"--\")\n args.append(contentsOf: self.commandLine.initArgs)\n }\n\n return args.joined(separator: \" \")\n }\n}\n\npublic protocol VZInterface {\n func device() throws -> VZVirtioNetworkDeviceConfiguration\n}\n\nextension NATInterface: VZInterface {\n public func device() throws -> VZVirtioNetworkDeviceConfiguration {\n let config = VZVirtioNetworkDeviceConfiguration()\n if let macAddress = self.macAddress {\n guard let mac = VZMACAddress(string: macAddress) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid mac address \\(macAddress)\")\n }\n config.macAddress = mac\n }\n config.attachment = VZNATNetworkDeviceAttachment()\n return config\n }\n}\n\n#endif\n"], ["/containerization/vminitd/Sources/vminitd/VsockProxy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationIO\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport SendableProperty\n\nfinal class VsockProxy: Sendable {\n enum Action {\n case listen\n case dial\n }\n\n private enum SocketType {\n case unix\n case vsock\n }\n\n init(\n id: String,\n action: Action,\n port: UInt32,\n path: URL,\n udsPerms: UInt32?,\n log: Logger? = nil\n ) {\n self.id = id\n self.action = action\n self.port = port\n self.path = path\n self.udsPerms = udsPerms\n self.log = log\n }\n\n public let id: String\n private let path: URL\n private let action: Action\n private let port: UInt32\n private let udsPerms: UInt32?\n private let log: Logger?\n\n @SendableProperty\n private var listener: Socket?\n private let task = Mutex?>(nil)\n}\n\nextension VsockProxy {\n func close() throws {\n guard let listener else {\n return\n }\n\n try listener.close()\n let fm = FileManager.default\n if fm.fileExists(atPath: self.path.path) {\n try FileManager.default.removeItem(at: self.path)\n }\n let task = task.withLock { $0 }\n task?.cancel()\n }\n\n func start() throws {\n switch self.action {\n case .dial:\n try dialHost()\n case .listen:\n try dialGuest()\n }\n }\n\n private func dialHost() throws {\n let fm = FileManager.default\n\n let parentDir = self.path.deletingLastPathComponent()\n try fm.createDirectory(\n at: parentDir,\n withIntermediateDirectories: true\n )\n\n let type = try UnixType(\n path: self.path.path,\n perms: self.udsPerms,\n unlinkExisting: true\n )\n let uds = try Socket(type: type)\n try uds.listen()\n listener = uds\n\n try self.acceptLoop(socketType: .unix)\n }\n\n private func dialGuest() throws {\n let type = VsockType(\n port: self.port,\n cid: VsockType.anyCID\n )\n let vsock = try Socket(type: type)\n try vsock.listen()\n listener = vsock\n\n try self.acceptLoop(socketType: .vsock)\n }\n\n private func acceptLoop(socketType: SocketType) throws {\n guard let listener else {\n return\n }\n\n let stream = try listener.acceptStream()\n let task = Task {\n do {\n for try await conn in stream {\n Task {\n do {\n try await handleConn(\n conn: conn,\n connType: socketType\n )\n } catch {\n self.log?.error(\"failed to handle connection: \\(error)\")\n }\n }\n }\n } catch {\n self.log?.error(\"failed to accept connection: \\(error)\")\n }\n }\n self.task.withLock { $0 = task }\n }\n\n private func handleConn(\n conn: ContainerizationOS.Socket,\n connType: SocketType\n ) async throws {\n try await withCheckedThrowingContinuation { (c: CheckedContinuation) in\n do {\n // `relayTo` isn't used concurrently.\n nonisolated(unsafe) var relayTo: ContainerizationOS.Socket\n\n switch connType {\n case .unix:\n let type = VsockType(\n port: self.port,\n cid: VsockType.hostCID\n )\n relayTo = try Socket(\n type: type,\n closeOnDeinit: false\n )\n case .vsock:\n let type = try UnixType(path: self.path.path)\n relayTo = try Socket(\n type: type,\n closeOnDeinit: false\n )\n }\n\n try relayTo.connect()\n\n // `clientFile` isn't used concurrently.\n nonisolated(unsafe) var clientFile = OSFile.SpliceFile(fd: conn.fileDescriptor)\n // `serverFile` isn't used concurrently.\n nonisolated(unsafe) var serverFile = OSFile.SpliceFile(fd: relayTo.fileDescriptor)\n\n let cleanup = { @Sendable in\n do {\n try ProcessSupervisor.default.poller.delete(clientFile.fileDescriptor)\n try ProcessSupervisor.default.poller.delete(serverFile.fileDescriptor)\n try conn.close()\n try relayTo.close()\n } catch {\n self.log?.error(\"Failed to clean up vsock proxy: \\(error)\")\n }\n c.resume()\n }\n\n try! ProcessSupervisor.default.poller.add(clientFile.fileDescriptor, mask: EPOLLIN | EPOLLOUT) { mask in\n if mask.readyToRead {\n do {\n let (_, _, action) = try OSFile.splice(from: &clientFile, to: &serverFile)\n if action == .eof || action == .brokenPipe {\n return cleanup()\n }\n } catch {\n return cleanup()\n }\n }\n\n if mask.readyToWrite {\n do {\n let (_, _, action) = try OSFile.splice(from: &serverFile, to: &clientFile)\n if action == .eof || action == .brokenPipe {\n return cleanup()\n }\n } catch {\n return cleanup()\n }\n }\n\n if mask.isHangup {\n return cleanup()\n }\n }\n\n try! ProcessSupervisor.default.poller.add(serverFile.fileDescriptor, mask: EPOLLIN | EPOLLOUT) { mask in\n if mask.readyToRead {\n do {\n let (_, _, action) = try OSFile.splice(from: &serverFile, to: &clientFile)\n if action == .eof || action == .brokenPipe {\n return cleanup()\n }\n } catch {\n return cleanup()\n }\n }\n\n if mask.readyToWrite {\n do {\n let (_, _, action) = try OSFile.splice(from: &clientFile, to: &serverFile)\n if action == .eof || action == .brokenPipe {\n return cleanup()\n }\n } catch {\n return cleanup()\n }\n }\n\n if mask.isHangup {\n return cleanup()\n }\n }\n } catch {\n c.resume(throwing: error)\n }\n }\n }\n}\n"], ["/containerization/Sources/Integration/ProcessTests.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Crypto\nimport Foundation\nimport Logging\n\nextension IntegrationSuite {\n func testProcessTrue() async throws {\n let id = \"test-process-true\"\n\n let bs = try await bootstrap()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/true\"]\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n }\n\n func testProcessFalse() async throws {\n let id = \"test-process-false\"\n\n let bs = try await bootstrap()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/false\"]\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 1 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 1\")\n }\n }\n\n final class BufferWriter: Writer {\n nonisolated(unsafe) var data = Data()\n\n func write(_ data: Data) throws {\n guard data.count > 0 else {\n return\n }\n self.data.append(data)\n }\n }\n\n final class StdinBuffer: ReaderStream {\n let data: Data\n\n init(data: Data) {\n self.data = data\n }\n\n func stream() -> AsyncStream {\n let (stream, cont) = AsyncStream.makeStream()\n cont.yield(self.data)\n cont.finish()\n return stream\n }\n }\n\n func testProcessEchoHi() async throws {\n let id = \"test-process-echo-hi\"\n let bs = try await bootstrap()\n\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/echo\", \"hi\"]\n config.process.stdout = buffer\n }\n\n do {\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 1\")\n }\n\n guard String(data: buffer.data, encoding: .utf8) == \"hi\\n\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned on stdout 'hi' != '\\(String(data: buffer.data, encoding: .utf8)!)'\")\n }\n } catch {\n try? await container.stop()\n throw error\n }\n }\n\n func testMultipleConcurrentProcesses() async throws {\n let id = \"test-concurrent-processes\"\n\n let bs = try await bootstrap()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/sleep\", \"1000\"]\n }\n\n do {\n try await container.create()\n try await container.start()\n\n try await withThrowingTaskGroup(of: Void.self) { group in\n for i in 0...80 {\n let exec = try await container.exec(\"exec-\\(i)\") { config in\n config.arguments = [\"/bin/true\"]\n }\n\n group.addTask {\n try await exec.start()\n let status = try await exec.wait()\n if status != 0 {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n try await exec.delete()\n }\n }\n\n // wait for all the exec'd processes.\n try await group.waitForAll()\n print(\"all group processes exit\")\n\n // kill the init process.\n try await container.kill(SIGKILL)\n let status = try await container.wait()\n try await container.stop()\n print(\"\\(status)\")\n }\n } catch {\n throw error\n }\n }\n\n func testMultipleConcurrentProcessesOutputStress() async throws {\n let id = \"test-concurrent-processes-output-stress\"\n let bs = try await bootstrap()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/sleep\", \"1000\"]\n }\n\n do {\n try await container.create()\n try await container.start()\n\n let buffer = BufferWriter()\n let exec = try await container.exec(\"expected-value\") { config in\n config.arguments = [\n \"sh\",\n \"-c\",\n \"dd if=/dev/random of=/tmp/bytes bs=1M count=20 status=none ; sha256sum /tmp/bytes\",\n ]\n config.stdout = buffer\n }\n\n try await exec.start()\n let status = try await exec.wait()\n if status != 0 {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n let output = String(data: buffer.data, encoding: .utf8)!\n let expected = String(output.split(separator: \" \").first!)\n try await withThrowingTaskGroup(of: Void.self) { group in\n for i in 0...80 {\n let idx = i\n group.addTask {\n let buffer = BufferWriter()\n let exec = try await container.exec(\"exec-\\(idx)\") { config in\n config.arguments = [\"cat\", \"/tmp/bytes\"]\n config.stdout = buffer\n }\n try await exec.start()\n\n let status = try await exec.wait()\n if status != 0 {\n throw IntegrationError.assert(msg: \"process \\(idx) status \\(status) != 0\")\n }\n\n var hasher = SHA256()\n hasher.update(data: buffer.data)\n let hash = hasher.finalize().digestString.trimmingDigestPrefix\n guard hash == expected else {\n throw IntegrationError.assert(\n msg: \"process \\(idx) output \\(hash) != expected \\(expected)\")\n }\n try await exec.delete()\n }\n }\n\n // wait for all the exec'd processes.\n try await group.waitForAll()\n print(\"all group processes exit\")\n\n // kill the init process.\n try await container.kill(SIGKILL)\n try await container.wait()\n try await container.stop()\n }\n }\n }\n\n func testProcessUser() async throws {\n let id = \"test-process-user\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/usr/bin/id\"]\n config.process.user = .init(uid: 1, gid: 1, additionalGids: [1])\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n let expected = \"uid=1(bin) gid=1(bin) groups=1(bin)\"\n\n guard String(data: buffer.data, encoding: .utf8) == \"\\(expected)\\n\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned on stdout '\\(expected)' != '\\(String(data: buffer.data, encoding: .utf8)!)'\")\n }\n }\n\n // Ensure if we ask for a terminal we set TERM.\n func testProcessTtyEnvvar() async throws {\n let id = \"test-process-tty-envvar\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"env\"]\n config.process.terminal = true\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n guard let str = String(data: buffer.data, encoding: .utf8) else {\n throw IntegrationError.assert(\n msg: \"failed to convert standard output to a UTF8 string\")\n }\n\n let homeEnvvar = \"TERM=xterm\"\n guard str.contains(homeEnvvar) else {\n throw IntegrationError.assert(\n msg: \"process should have TERM environment variable defined\")\n }\n }\n\n // Make sure we set HOME by default if we can find it in /etc/passwd in the guest.\n func testProcessHomeEnvvar() async throws {\n let id = \"test-process-home-envvar\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"env\"]\n config.process.user = .init(uid: 0, gid: 0)\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n guard let str = String(data: buffer.data, encoding: .utf8) else {\n throw IntegrationError.assert(\n msg: \"failed to convert standard output to a UTF8 string\")\n }\n\n let homeEnvvar = \"HOME=/root\"\n guard str.contains(homeEnvvar) else {\n throw IntegrationError.assert(\n msg: \"process should have HOME environment variable defined\")\n }\n }\n\n func testProcessCustomHomeEnvvar() async throws {\n let id = \"test-process-custom-home-envvar\"\n\n let bs = try await bootstrap()\n let customHomeEnvvar = \"HOME=/tmp/custom/home\"\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"sh\", \"-c\", \"echo HOME=$HOME\"]\n config.process.environmentVariables.append(customHomeEnvvar)\n config.process.user = .init(uid: 0, gid: 0)\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n guard let output = String(data: buffer.data, encoding: .utf8) else {\n throw IntegrationError.assert(msg: \"failed to convert stdout to UTF8\")\n }\n\n guard output.contains(customHomeEnvvar) else {\n throw IntegrationError.assert(msg: \"process should have preserved custom HOME environment variable, expected \\(customHomeEnvvar), got: \\(output)\")\n }\n }\n\n func testHostname() async throws {\n let id = \"test-container-hostname\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/hostname\"]\n config.hostname = \"foo-bar\"\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n let expected = \"foo-bar\"\n\n guard String(data: buffer.data, encoding: .utf8) == \"\\(expected)\\n\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned on stdout '\\(expected)' != '\\(String(data: buffer.data, encoding: .utf8)!)'\")\n }\n }\n\n func testHostsFile() async throws {\n let id = \"test-container-hosts-file\"\n\n let bs = try await bootstrap()\n let entry = Hosts.Entry.localHostIPV4(comment: \"Testaroo\")\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"cat\", \"/etc/hosts\"]\n config.hosts = Hosts(entries: [entry])\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n let expected = entry.rendered\n guard String(data: buffer.data, encoding: .utf8) == \"\\(expected)\\n\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned on stdout '\\(expected)' != '\\(String(data: buffer.data, encoding: .utf8)!)'\")\n }\n }\n\n func testProcessStdin() async throws {\n let id = \"test-container-stdin\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"cat\"]\n config.process.stdin = StdinBuffer(data: \"Hello from test\".data(using: .utf8)!)\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n let expected = \"Hello from test\"\n\n guard String(data: buffer.data, encoding: .utf8) == \"\\(expected)\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned on stdout '\\(expected)' != '\\(String(data: buffer.data, encoding: .utf8)!)'\")\n }\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/ManagedContainer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nactor ManagedContainer {\n let id: String\n let initProcess: ManagedProcess\n\n private let _log: Logger\n private let _bundle: ContainerizationOCI.Bundle\n private var _execs: [String: ManagedProcess] = [:]\n\n var pid: Int32 {\n self.initProcess.pid\n }\n\n init(\n id: String,\n stdio: HostStdio,\n spec: ContainerizationOCI.Spec,\n log: Logger\n ) throws {\n let bundle = try ContainerizationOCI.Bundle.create(\n path: Self.craftBundlePath(id: id),\n spec: spec\n )\n log.info(\"created bundle with spec \\(spec)\")\n\n let initProcess = try ManagedProcess(\n id: id,\n stdio: stdio,\n bundle: bundle,\n owningPid: nil,\n log: log\n )\n log.info(\"created managed init process\")\n\n self.initProcess = initProcess\n self.id = id\n self._bundle = bundle\n self._log = log\n }\n}\n\nextension ManagedContainer {\n private func ensureExecExists(_ id: String) throws {\n if self._execs[id] == nil {\n throw ContainerizationError(\n .invalidState,\n message: \"exec \\(id) does not exist in container \\(self.id)\"\n )\n }\n }\n\n func createExec(\n id: String,\n stdio: HostStdio,\n process: ContainerizationOCI.Process\n ) throws {\n // Write the process config to the bundle, and pass this on\n // over to ManagedProcess to deal with.\n try self._bundle.createExecSpec(\n id: id,\n process: process\n )\n let process = try ManagedProcess(\n id: id,\n stdio: stdio,\n bundle: self._bundle,\n owningPid: self.initProcess.pid,\n log: self._log\n )\n self._execs[id] = process\n }\n\n func start(execID: String) async throws -> Int32 {\n let proc = try self.getExecOrInit(execID: execID)\n return try await ProcessSupervisor.default.start(process: proc)\n }\n\n func wait(execID: String) async throws -> Int32 {\n let proc = try self.getExecOrInit(execID: execID)\n return await proc.wait()\n }\n\n func kill(execID: String, _ signal: Int32) throws {\n let proc = try self.getExecOrInit(execID: execID)\n try proc.kill(signal)\n }\n\n func resize(execID: String, size: Terminal.Size) throws {\n let proc = try self.getExecOrInit(execID: execID)\n try proc.resize(size: size)\n }\n\n func closeStdin(execID: String) throws {\n let proc = try self.getExecOrInit(execID: execID)\n try proc.closeStdin()\n }\n\n func deleteExec(id: String) throws {\n try ensureExecExists(id)\n do {\n try self._bundle.deleteExecSpec(id: id)\n } catch {\n self._log.error(\"failed to remove exec spec from filesystem: \\(error)\")\n }\n self._execs.removeValue(forKey: id)\n }\n\n func delete() throws {\n try self._bundle.delete()\n }\n\n func getExecOrInit(execID: String) throws -> ManagedProcess {\n if execID == self.id {\n return self.initProcess\n }\n guard let proc = self._execs[execID] else {\n throw ContainerizationError(\n .invalidState,\n message: \"exec \\(execID) does not exist in container \\(self.id)\"\n )\n }\n return proc\n }\n}\n\nextension ContainerizationOCI.Bundle {\n func createExecSpec(id: String, process: ContainerizationOCI.Process) throws {\n let specDir = self.path.appending(path: \"execs/\\(id)\")\n\n let fm = FileManager.default\n try fm.createDirectory(\n atPath: specDir.path,\n withIntermediateDirectories: true\n )\n\n let specData = try JSONEncoder().encode(process)\n let processConfigPath = specDir.appending(path: \"process.json\")\n try specData.write(to: processConfigPath)\n }\n\n func getExecSpecPath(id: String) -> URL {\n self.path.appending(path: \"execs/\\(id)/process.json\")\n }\n\n func deleteExecSpec(id: String) throws {\n let specDir = self.path.appending(path: \"execs/\\(id)\")\n\n let fm = FileManager.default\n try fm.removeItem(at: specDir)\n }\n}\n\nextension ManagedContainer {\n static func craftBundlePath(id: String) -> URL {\n URL(fileURLWithPath: \"/run/container\").appending(path: id)\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/StandardIO.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport Synchronization\n\nfinal class StandardIO: ManagedProcess.IO & Sendable {\n private struct State {\n var stdin: IOPair?\n var stdout: IOPair?\n var stderr: IOPair?\n\n var stdinPipe: Pipe?\n var stdoutPipe: Pipe?\n var stderrPipe: Pipe?\n }\n\n private let log: Logger?\n private let hostStdio: HostStdio\n private let state: Mutex\n\n init(\n stdio: HostStdio,\n log: Logger?\n ) {\n self.hostStdio = stdio\n self.log = log\n self.state = Mutex(State())\n }\n\n func start(process: inout Command) throws {\n try self.state.withLock {\n if let stdinPort = self.hostStdio.stdin {\n let inPipe = Pipe()\n process.stdin = inPipe.fileHandleForReading\n $0.stdinPipe = inPipe\n\n let type = VsockType(\n port: stdinPort,\n cid: VsockType.hostCID\n )\n let stdinSocket = try Socket(type: type, closeOnDeinit: false)\n try stdinSocket.connect()\n\n let pair = IOPair(\n readFrom: stdinSocket,\n writeTo: inPipe.fileHandleForWriting,\n logger: log\n )\n $0.stdin = pair\n\n try pair.relay()\n }\n\n if let stdoutPort = self.hostStdio.stdout {\n let outPipe = Pipe()\n process.stdout = outPipe.fileHandleForWriting\n $0.stdoutPipe = outPipe\n\n let type = VsockType(\n port: stdoutPort,\n cid: VsockType.hostCID\n )\n let stdoutSocket = try Socket(type: type, closeOnDeinit: false)\n try stdoutSocket.connect()\n\n let pair = IOPair(\n readFrom: outPipe.fileHandleForReading,\n writeTo: stdoutSocket,\n logger: log\n )\n $0.stdout = pair\n\n try pair.relay()\n }\n\n if let stderrPort = self.hostStdio.stderr {\n let errPipe = Pipe()\n process.stderr = errPipe.fileHandleForWriting\n $0.stderrPipe = errPipe\n\n let type = VsockType(\n port: stderrPort,\n cid: VsockType.hostCID\n )\n let stderrSocket = try Socket(type: type, closeOnDeinit: false)\n try stderrSocket.connect()\n\n let pair = IOPair(\n readFrom: errPipe.fileHandleForReading,\n writeTo: stderrSocket,\n logger: log\n )\n $0.stderr = pair\n\n try pair.relay()\n }\n }\n }\n\n // NOP\n func resize(size: Terminal.Size) throws {}\n\n func closeStdin() throws {\n self.state.withLock {\n if let stdin = $0.stdin {\n stdin.close()\n $0.stdin = nil\n }\n }\n }\n\n func closeAfterExec() throws {\n try self.state.withLock {\n if let stdin = $0.stdinPipe {\n try stdin.fileHandleForReading.close()\n }\n if let stdout = $0.stdoutPipe {\n try stdout.fileHandleForWriting.close()\n }\n if let stderr = $0.stderrPipe {\n try stderr.fileHandleForWriting.close()\n }\n }\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/TerminalIO.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport Synchronization\n\nfinal class TerminalIO: ManagedProcess.IO & Sendable {\n private struct State {\n var stdin: IOPair?\n var stdout: IOPair?\n }\n\n private let parent: Terminal\n private let child: Terminal\n private let log: Logger?\n private let hostStdio: HostStdio\n private let state: Mutex\n\n init(\n stdio: HostStdio,\n log: Logger?\n ) throws {\n let pair = try Terminal.create()\n self.parent = pair.parent\n self.child = pair.child\n self.state = Mutex(State())\n self.hostStdio = stdio\n self.log = log\n }\n\n func resize(size: Terminal.Size) throws {\n try parent.resize(size: size)\n }\n\n func start(process: inout Command) throws {\n try self.state.withLock {\n let ptyHandle = self.child.handle\n let useHandles = self.hostStdio.stdin != nil || self.hostStdio.stdout != nil\n // We currently set stdin to the controlling terminal always, so\n // it must be a valid pty descriptor.\n process.stdin = useHandles ? ptyHandle : nil\n\n let stdoutHandle = useHandles ? ptyHandle : nil\n process.stdout = stdoutHandle\n process.stderr = stdoutHandle\n\n if let stdinPort = self.hostStdio.stdin {\n let type = VsockType(\n port: stdinPort,\n cid: VsockType.hostCID\n )\n let stdinSocket = try Socket(type: type, closeOnDeinit: false)\n try stdinSocket.connect()\n\n let pair = IOPair(\n readFrom: stdinSocket,\n writeTo: self.parent.handle,\n logger: self.log\n )\n $0.stdin = pair\n\n try pair.relay()\n }\n\n if let stdoutPort = self.hostStdio.stdout {\n let type = VsockType(\n port: stdoutPort,\n cid: VsockType.hostCID\n )\n let stdoutSocket = try Socket(type: type, closeOnDeinit: false)\n try stdoutSocket.connect()\n\n let pair = IOPair(\n readFrom: self.parent.handle,\n writeTo: stdoutSocket,\n logger: self.log\n )\n $0.stdout = pair\n\n try pair.relay()\n }\n }\n }\n\n func closeStdin() throws {\n self.state.withLock {\n $0.stdin?.close()\n }\n }\n\n func closeAfterExec() throws {\n try child.close()\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/RegistryClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport NIO\nimport NIOHTTP1\n\n#if os(macOS)\nimport Network\n#endif\n\n/// Data used to control retry behavior for `RegistryClient`.\npublic struct RetryOptions: Sendable {\n /// The maximum number of retries to attempt before failing.\n public var maxRetries: Int\n /// The retry interval in nanoseconds.\n public var retryInterval: UInt64\n /// A provided closure to handle if a given HTTP response should be\n /// retried.\n public var shouldRetry: (@Sendable (HTTPClientResponse) -> Bool)?\n\n public init(maxRetries: Int, retryInterval: UInt64, shouldRetry: (@Sendable (HTTPClientResponse) -> Bool)? = nil) {\n self.maxRetries = maxRetries\n self.retryInterval = retryInterval\n self.shouldRetry = shouldRetry\n }\n}\n\n/// A client for interacting with OCI compliant container registries.\npublic final class RegistryClient: ContentClient {\n private static let defaultRetryOptions = RetryOptions(\n maxRetries: 3,\n retryInterval: 1_000_000_000,\n shouldRetry: ({ response in\n response.status.code >= 500\n })\n )\n\n let client: HTTPClient\n let base: URLComponents\n let clientID: String\n let authentication: Authentication?\n let retryOptions: RetryOptions?\n let bufferSize: Int\n\n public convenience init(\n reference: String,\n insecure: Bool = false,\n auth: Authentication? = nil,\n logger: Logger? = nil\n ) throws {\n let ref = try Reference.parse(reference)\n guard let domain = ref.resolvedDomain else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid domain for image reference \\(reference)\")\n }\n let scheme = insecure ? \"http\" : \"https\"\n let _url = \"\\(scheme)://\\(domain)\"\n guard let url = URL(string: _url) else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot convert \\(_url) to URL\")\n }\n guard let host = url.host else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid host \\(domain)\")\n }\n let port = url.port\n self.init(\n host: host,\n scheme: scheme,\n port: port,\n authentication: auth,\n retryOptions: Self.defaultRetryOptions\n )\n }\n\n public init(\n host: String,\n scheme: String? = \"https\",\n port: Int? = nil,\n authentication: Authentication? = nil,\n clientID: String? = nil,\n retryOptions: RetryOptions? = nil,\n bufferSize: Int = Int(4.mib()),\n logger: Logger? = nil\n ) {\n var components = URLComponents()\n components.scheme = scheme\n components.host = host\n components.port = port\n\n self.base = components\n self.clientID = clientID ?? \"containerization-registry-client\"\n self.authentication = authentication\n self.retryOptions = retryOptions\n self.bufferSize = bufferSize\n var httpConfiguration = HTTPClient.Configuration()\n let proxyConfig: HTTPClient.Configuration.Proxy? = {\n let proxyEnv = ProcessInfo.processInfo.environment[\"HTTP_PROXY\"]\n guard let proxyEnv else {\n return nil\n }\n guard let url = URL(string: proxyEnv), let host = url.host(), let port = url.port else {\n return nil\n }\n return .server(host: host, port: port)\n }()\n httpConfiguration.proxy = proxyConfig\n if let logger {\n self.client = HTTPClient(eventLoopGroupProvider: .singleton, configuration: httpConfiguration, backgroundActivityLogger: logger)\n } else {\n self.client = HTTPClient(eventLoopGroupProvider: .singleton, configuration: httpConfiguration)\n }\n }\n\n deinit {\n _ = client.shutdown()\n }\n\n func host() -> String {\n base.host ?? \"\"\n }\n\n internal func request(\n components: URLComponents,\n method: HTTPMethod = .GET,\n bodyClosure: () throws -> HTTPClientRequest.Body? = { nil },\n headers: [(String, String)]? = nil,\n closure: (HTTPClientResponse) async throws -> T\n ) async throws -> T {\n guard let path = components.url?.absoluteString else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid url \\(components.path)\")\n }\n\n var request = HTTPClientRequest(url: path)\n request.method = method\n\n var currentToken: TokenResponse?\n let token: String? = try await {\n if let basicAuth = authentication {\n return try await basicAuth.token()\n }\n return nil\n }()\n\n if let token {\n request.headers.add(name: \"Authorization\", value: \"\\(token)\")\n }\n\n // Add any arbitrary headers\n headers?.forEach { (k, v) in request.headers.add(name: k, value: v) }\n var retryCount = 0\n var response: HTTPClientResponse?\n while true {\n request.body = try bodyClosure()\n do {\n let _response = try await client.execute(request, deadline: .distantFuture)\n response = _response\n if _response.status == .unauthorized || _response.status == .forbidden {\n let authHeader = _response.headers[TokenRequest.authenticateHeaderName]\n let tokenRequest: TokenRequest\n do {\n tokenRequest = try self.createTokenRequest(parsing: authHeader)\n } catch {\n // The server did not tell us how to authenticate our requests,\n // Or we do not support scheme the server is requesting for.\n // Throw the 401/403 to the caller, and let them decide how to proceed.\n throw RegistryClient.Error.invalidStatus(url: path, _response.status, reason: String(describing: error))\n }\n if let ct = currentToken, ct.isValid(scope: tokenRequest.scope) {\n break\n }\n\n do {\n let _currentToken = try await fetchToken(request: tokenRequest)\n guard let token = _currentToken.getToken() else {\n throw ContainerizationError(.internalError, message: \"Failed to fetch Bearer token\")\n }\n currentToken = _currentToken\n request.headers.replaceOrAdd(name: \"Authorization\", value: token)\n retryCount += 1\n } catch let err as RegistryClient.Error {\n guard case .invalidStatus(_, let status, _) = err else {\n throw err\n }\n if status == .unauthorized || status == .forbidden {\n throw RegistryClient.Error.invalidStatus(url: path, _response.status, reason: \"Access denied or wrong credentials\")\n }\n\n throw err\n }\n\n continue\n }\n guard let retryOptions = self.retryOptions else {\n break\n }\n guard retryCount < retryOptions.maxRetries else {\n break\n }\n guard let shouldRetry = retryOptions.shouldRetry, shouldRetry(_response) else {\n break\n }\n retryCount += 1\n try await Task.sleep(nanoseconds: retryOptions.retryInterval)\n continue\n } catch let err as RegistryClient.Error {\n throw err\n } catch {\n #if os(macOS)\n if let err = error as? NWError {\n if err.errorCode == kDNSServiceErr_NoSuchRecord {\n throw ContainerizationError(.internalError, message: \"No Such DNS Record \\(host())\")\n }\n }\n #endif\n guard let retryOptions = self.retryOptions, retryCount < retryOptions.maxRetries else {\n throw error\n }\n retryCount += 1\n try await Task.sleep(nanoseconds: retryOptions.retryInterval)\n }\n }\n guard let response else {\n throw ContainerizationError(.internalError, message: \"Invalid response\")\n }\n return try await closure(response)\n }\n\n internal func requestData(\n components: URLComponents,\n headers: [(String, String)]? = nil\n ) async throws -> Data {\n let bytes: ByteBuffer = try await requestBuffer(components: components, headers: headers)\n return Data(buffer: bytes)\n }\n\n internal func requestBuffer(\n components: URLComponents,\n headers: [(String, String)]? = nil\n ) async throws -> ByteBuffer {\n try await request(components: components, method: .GET, headers: headers) { response in\n guard response.status == .ok else {\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n\n return try await response.body.collect(upTo: self.bufferSize)\n }\n }\n\n internal func requestJSON(\n components: URLComponents,\n headers: [(String, String)]? = nil\n ) async throws -> T {\n let buffer = try await self.requestBuffer(components: components, headers: headers)\n return try JSONDecoder().decode(T.self, from: buffer)\n }\n\n /// A minimal endpoint, mounted at /v2/ will provide version support information based on its response statuses.\n /// See https://distribution.github.io/distribution/spec/api/#api-version-check\n public func ping() async throws {\n var components = base\n components.path = \"/v2/\"\n\n try await request(components: components) { response in\n guard response.status == .ok else {\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n }\n }\n}\n"], ["/containerization/Sources/Containerization/Image/ImageStore/ImageStore+Import.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\nextension ImageStore {\n internal struct ImportOperation {\n static let decoder = JSONDecoder()\n\n let client: ContentClient\n let ingestDir: URL\n let contentStore: ContentStore\n let progress: ProgressHandler?\n let name: String\n\n init(name: String, contentStore: ContentStore, client: ContentClient, ingestDir: URL, progress: ProgressHandler? = nil) {\n self.client = client\n self.ingestDir = ingestDir\n self.contentStore = contentStore\n self.progress = progress\n self.name = name\n }\n\n /// Pull the required image layers for the provided descriptor and platform(s) into the given directory using the provided client. Returns a descriptor to the Index manifest.\n internal func `import`(root: Descriptor, matcher: (ContainerizationOCI.Platform) -> Bool) async throws -> Descriptor {\n var toProcess = [root]\n while !toProcess.isEmpty {\n // Count the total number of blobs and their size\n if let progress {\n var size: Int64 = 0\n for desc in toProcess {\n size += desc.size\n }\n await progress([\n ProgressEvent(event: \"add-total-size\", value: size),\n ProgressEvent(event: \"add-total-items\", value: toProcess.count),\n ])\n }\n\n try await self.fetchAll(toProcess)\n let children = try await self.walk(toProcess)\n let filtered = try filterPlatforms(matcher: matcher, children)\n toProcess = filtered.uniqued { $0.digest }\n }\n\n guard root.mediaType != MediaTypes.dockerManifestList && root.mediaType != MediaTypes.index else {\n return root\n }\n\n // Create an index for the root descriptor and write it to the content store\n let index = try await self.createIndex(for: root)\n // In cases where the root descriptor pointed to `MediaTypes.imageManifest`\n // Or `MediaTypes.dockerManifest`, it is required that we check the supported platform\n // matches the platforms we were asked to pull. This can be done only after we created\n // the Index.\n let supportedPlatforms = index.manifests.compactMap { $0.platform }\n guard supportedPlatforms.allSatisfy(matcher) else {\n throw ContainerizationError(.unsupported, message: \"Image \\(root.digest) does not support required platforms\")\n }\n let writer = try ContentWriter(for: self.ingestDir)\n let result = try writer.create(from: index)\n return Descriptor(\n mediaType: MediaTypes.index,\n digest: result.digest.digestString,\n size: Int64(result.size))\n }\n\n private func getManifestContent(descriptor: Descriptor) async throws -> T {\n do {\n if let content = try await self.contentStore.get(digest: descriptor.digest.trimmingDigestPrefix) {\n return try content.decode()\n }\n if let content = try? LocalContent(path: ingestDir.appending(path: descriptor.digest.trimmingDigestPrefix)) {\n return try content.decode()\n }\n return try await self.client.fetch(name: name, descriptor: descriptor)\n } catch {\n throw ContainerizationError(.internalError, message: \"Cannot fetch content with digest \\(descriptor.digest)\", cause: error)\n }\n }\n\n private func walk(_ descriptors: [Descriptor]) async throws -> [Descriptor] {\n var out: [Descriptor] = []\n for desc in descriptors {\n let mediaType = desc.mediaType\n switch mediaType {\n case MediaTypes.index, MediaTypes.dockerManifestList:\n let index: Index = try await self.getManifestContent(descriptor: desc)\n out.append(contentsOf: index.manifests)\n case MediaTypes.imageManifest, MediaTypes.dockerManifest:\n let manifest: Manifest = try await self.getManifestContent(descriptor: desc)\n out.append(manifest.config)\n out.append(contentsOf: manifest.layers)\n default:\n // TODO: Explicitly handle other content types\n continue\n }\n }\n return out\n }\n\n private func fetchAll(_ descriptors: [Descriptor]) async throws {\n try await withThrowingTaskGroup(of: Void.self) { group in\n var iterator = descriptors.makeIterator()\n for _ in 0..<8 {\n if let desc = iterator.next() {\n group.addTask {\n try await fetch(desc)\n }\n }\n }\n for try await _ in group {\n if let desc = iterator.next() {\n group.addTask {\n try await fetch(desc)\n }\n }\n }\n }\n }\n\n private func fetch(_ descriptor: Descriptor) async throws {\n if let found = try await self.contentStore.get(digest: descriptor.digest) {\n try FileManager.default.copyItem(at: found.path, to: ingestDir.appendingPathComponent(descriptor.digest.trimmingDigestPrefix))\n await progress?([\n // Count the size of the blob\n ProgressEvent(event: \"add-size\", value: descriptor.size),\n // Count the number of blobs\n ProgressEvent(event: \"add-items\", value: 1),\n ])\n return\n }\n\n if descriptor.size > 1.mib() {\n try await self.fetchBlob(descriptor)\n } else {\n try await self.fetchData(descriptor)\n }\n // Count the number of blobs\n await progress?([\n ProgressEvent(event: \"add-items\", value: 1)\n ])\n }\n\n private func fetchBlob(_ descriptor: Descriptor) async throws {\n let id = UUID().uuidString\n let fm = FileManager.default\n let tempFile = ingestDir.appendingPathComponent(id)\n let (_, digest) = try await client.fetchBlob(name: name, descriptor: descriptor, into: tempFile, progress: progress)\n guard digest.digestString == descriptor.digest else {\n throw ContainerizationError(.internalError, message: \"Digest mismatch expected \\(descriptor.digest), got \\(digest.digestString)\")\n }\n do {\n try fm.moveItem(at: tempFile, to: ingestDir.appendingPathComponent(digest.encoded))\n } catch let err as NSError {\n guard err.code == NSFileWriteFileExistsError else {\n throw err\n }\n try fm.removeItem(at: tempFile)\n }\n }\n\n @discardableResult\n private func fetchData(_ descriptor: Descriptor) async throws -> Data {\n let data = try await client.fetchData(name: name, descriptor: descriptor)\n let writer = try ContentWriter(for: ingestDir)\n let result = try writer.write(data)\n if let progress {\n let size = Int64(result.size)\n await progress([\n ProgressEvent(event: \"add-size\", value: size)\n ])\n }\n guard result.digest.digestString == descriptor.digest else {\n throw ContainerizationError(.internalError, message: \"Digest mismatch expected \\(descriptor.digest), got \\(result.digest.digestString)\")\n }\n return data\n }\n\n private func createIndex(for root: Descriptor) async throws -> Index {\n switch root.mediaType {\n case MediaTypes.index, MediaTypes.dockerManifestList:\n return try await self.getManifestContent(descriptor: root)\n case MediaTypes.imageManifest, MediaTypes.dockerManifest:\n let supportedPlatforms = try await getSupportedPlatforms(for: root)\n guard supportedPlatforms.count == 1 else {\n throw ContainerizationError(\n .internalError,\n message:\n \"Descriptor \\(root.mediaType) with digest \\(root.digest) does not list any supported platform or supports more than one platform. Supported platforms = \\(supportedPlatforms)\"\n )\n }\n let platform = supportedPlatforms.first!\n var root = root\n root.platform = platform\n let index = ContainerizationOCI.Index(\n schemaVersion: 2, manifests: [root],\n annotations: [\n // indicate that this is a synthesized index which is not directly user facing\n AnnotationKeys.containerizationIndexIndirect: \"true\"\n ])\n return index\n default:\n throw ContainerizationError(.internalError, message: \"Failed to create index for descriptor \\(root.digest), media type \\(root.mediaType)\")\n }\n }\n\n private func getSupportedPlatforms(for root: Descriptor) async throws -> [ContainerizationOCI.Platform] {\n var supportedPlatforms: [ContainerizationOCI.Platform] = []\n var toProcess = [root]\n while !toProcess.isEmpty {\n let children = try await self.walk(toProcess)\n for child in children {\n if let p = child.platform {\n supportedPlatforms.append(p)\n continue\n }\n switch child.mediaType {\n case MediaTypes.imageConfig, MediaTypes.dockerImageConfig:\n let config: ContainerizationOCI.Image = try await self.getManifestContent(descriptor: child)\n let p = ContainerizationOCI.Platform(\n arch: config.architecture, os: config.os, osFeatures: config.osFeatures, variant: config.variant\n )\n supportedPlatforms.append(p)\n default:\n continue\n }\n }\n toProcess = children\n }\n return supportedPlatforms\n }\n\n }\n}\n"], ["/containerization/Sources/Containerization/ContainerManager.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport ContainerizationExtras\nimport Virtualization\nimport vmnet\n\n/// A manager for creating and running containers.\n/// Supports container networking options.\npublic struct ContainerManager: Sendable {\n public let imageStore: ImageStore\n private let vmm: VirtualMachineManager\n private let network: Network?\n\n private var containerRoot: URL {\n self.imageStore.path.appendingPathComponent(\"containers\")\n }\n\n /// A network that can allocate and release interfaces for use with containers.\n public protocol Network: Sendable {\n func create(_ id: String) throws -> Interface?\n func release(_ id: String) throws\n }\n\n /// A network backed by vmnet on macOS.\n @available(macOS 26.0, *)\n public struct VmnetNetwork: Network {\n private let allocator: Allocator\n nonisolated(unsafe) private let reference: vmnet_network_ref\n\n /// The IPv4 subnet of this network.\n public let subnet: CIDRAddress\n\n /// The gateway address of this network.\n public var gateway: IPv4Address {\n subnet.gateway\n }\n\n struct Allocator: Sendable {\n private let addressAllocator: any AddressAllocator\n private let cidr: CIDRAddress\n private var allocations: [String: UInt32]\n\n init(cidr: CIDRAddress) throws {\n self.cidr = cidr\n self.allocations = .init()\n let size = Int(cidr.upper.value - cidr.lower.value - 3)\n self.addressAllocator = try UInt32.rotatingAllocator(\n lower: cidr.lower.value + 2,\n size: UInt32(size)\n )\n }\n\n func allocate(_ id: String) throws -> String {\n if allocations[id] != nil {\n throw ContainerizationError(.exists, message: \"allocation with id \\(id) already exists\")\n }\n let index = try addressAllocator.allocate()\n let ip = IPv4Address(fromValue: index)\n return try CIDRAddress(ip, prefixLength: cidr.prefixLength).description\n }\n\n func release(_ id: String) throws {\n if let index = self.allocations[id] {\n try addressAllocator.release(index)\n }\n }\n }\n\n /// A network interface supporting the vmnet_network_ref.\n public struct Interface: Containerization.Interface, VZInterface, Sendable {\n public let address: String\n public let gateway: String?\n public let macAddress: String?\n\n nonisolated(unsafe) private let reference: vmnet_network_ref\n\n public init(\n reference: vmnet_network_ref,\n address: String,\n gateway: String,\n macAddress: String? = nil\n ) {\n self.address = address\n self.gateway = gateway\n self.macAddress = macAddress\n self.reference = reference\n }\n\n /// Returns the underlying `VZVirtioNetworkDeviceConfiguration`.\n public func device() throws -> VZVirtioNetworkDeviceConfiguration {\n let config = VZVirtioNetworkDeviceConfiguration()\n if let macAddress = self.macAddress {\n guard let mac = VZMACAddress(string: macAddress) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid mac address \\(macAddress)\")\n }\n config.macAddress = mac\n }\n config.attachment = VZVmnetNetworkDeviceAttachment(network: self.reference)\n return config\n }\n }\n\n /// Creates a new network.\n /// - Parameter subnet: The subnet to use for this network.\n public init(subnet: String? = nil) throws {\n var status: vmnet_return_t = .VMNET_FAILURE\n guard let config = vmnet_network_configuration_create(.VMNET_SHARED_MODE, &status) else {\n throw ContainerizationError(.unsupported, message: \"failed to create vmnet config with status \\(status)\")\n }\n\n vmnet_network_configuration_disable_dhcp(config)\n\n if let subnet {\n try Self.configureSubnet(config, subnet: try CIDRAddress(subnet))\n }\n\n guard let ref = vmnet_network_create(config, &status), status == .VMNET_SUCCESS else {\n throw ContainerizationError(.unsupported, message: \"failed to create vmnet network with status \\(status)\")\n }\n\n let cidr = try Self.getSubnet(ref)\n\n self.allocator = try .init(cidr: cidr)\n self.subnet = cidr\n self.reference = ref\n }\n\n /// Returns a new interface for use with a container.\n /// - Parameter id: The container ID.\n public func create(_ id: String) throws -> Containerization.Interface? {\n let address = try allocator.allocate(id)\n return Self.Interface(\n reference: self.reference,\n address: address,\n gateway: self.gateway.description,\n )\n }\n\n /// Performs cleanup of an interface.\n /// - Parameter id: The container ID.\n public func release(_ id: String) throws {\n try allocator.release(id)\n }\n\n private static func getSubnet(_ ref: vmnet_network_ref) throws -> CIDRAddress {\n var subnet = in_addr()\n var mask = in_addr()\n vmnet_network_get_ipv4_subnet(ref, &subnet, &mask)\n\n let sa = UInt32(bigEndian: subnet.s_addr)\n let mv = UInt32(bigEndian: mask.s_addr)\n\n let lower = IPv4Address(fromValue: sa & mv)\n let upper = IPv4Address(fromValue: lower.value + ~mv)\n\n return try CIDRAddress(lower: lower, upper: upper)\n }\n\n private static func configureSubnet(_ config: vmnet_network_configuration_ref, subnet: CIDRAddress) throws {\n let gateway = subnet.gateway\n\n var ga = in_addr()\n inet_pton(AF_INET, gateway.description, &ga)\n\n let mask = IPv4Address(fromValue: subnet.prefixLength.prefixMask32)\n var ma = in_addr()\n inet_pton(AF_INET, mask.description, &ma)\n\n guard vmnet_network_configuration_set_ipv4_subnet(config, &ga, &ma) == .VMNET_SUCCESS else {\n throw ContainerizationError(.internalError, message: \"failed to set subnet \\(subnet) for network\")\n }\n }\n }\n\n /// Create a new manager with the provided kernel and initfs mount.\n public init(\n kernel: Kernel,\n initfs: Mount,\n network: Network? = nil\n ) throws {\n self.imageStore = ImageStore.default\n self.network = network\n try Self.createRootDirectory(path: self.imageStore.path)\n self.vmm = VZVirtualMachineManager(\n kernel: kernel,\n initialFilesystem: initfs,\n bootlog: self.imageStore.path.appendingPathComponent(\"bootlog.log\").absolutePath()\n )\n }\n\n /// Create a new manager with the provided kernel and image reference for the initfs.\n public init(\n kernel: Kernel,\n initfsReference: String,\n network: Network? = nil\n ) async throws {\n self.imageStore = ImageStore.default\n self.network = network\n try Self.createRootDirectory(path: self.imageStore.path)\n\n let initPath = self.imageStore.path.appendingPathComponent(\"initfs.ext4\")\n let initImage = try await self.imageStore.getInitImage(reference: initfsReference)\n let initfs = try await {\n do {\n return try await initImage.initBlock(at: initPath, for: .linuxArm)\n } catch let err as ContainerizationError {\n guard err.code == .exists else {\n throw err\n }\n return .block(\n format: \"ext4\",\n source: initPath.absolutePath(),\n destination: \"/\",\n options: [\"ro\"]\n )\n }\n }()\n\n self.vmm = VZVirtualMachineManager(\n kernel: kernel,\n initialFilesystem: initfs,\n bootlog: self.imageStore.path.appendingPathComponent(\"bootlog.log\").absolutePath()\n )\n }\n\n /// Create a new manager with the provided vmm and network.\n public init(\n vmm: any VirtualMachineManager,\n network: Network? = nil\n ) throws {\n self.imageStore = ImageStore.default\n try Self.createRootDirectory(path: self.imageStore.path)\n self.network = network\n self.vmm = vmm\n }\n\n private static func createRootDirectory(path: URL) throws {\n try FileManager.default.createDirectory(\n at: path.appendingPathComponent(\"containers\"),\n withIntermediateDirectories: true\n )\n }\n\n /// Returns a new container from the provided image reference.\n /// - Parameters:\n /// - id: The container ID.\n /// - reference: The image reference.\n /// - rootfsSizeInBytes: The size of the root filesystem in bytes. Defaults to 8 GiB.\n public func create(\n _ id: String,\n reference: String,\n rootfsSizeInBytes: UInt64 = 8.gib(),\n configuration: (inout LinuxContainer.Configuration) throws -> Void\n ) async throws -> LinuxContainer {\n let image = try await imageStore.get(reference: reference, pull: true)\n return try await create(\n id,\n image: image,\n rootfsSizeInBytes: rootfsSizeInBytes,\n configuration: configuration\n )\n }\n\n /// Returns a new container from the provided image.\n /// - Parameters:\n /// - id: The container ID.\n /// - image: The image.\n /// - rootfsSizeInBytes: The size of the root filesystem in bytes. Defaults to 8 GiB.\n public func create(\n _ id: String,\n image: Image,\n rootfsSizeInBytes: UInt64 = 8.gib(),\n configuration: (inout LinuxContainer.Configuration) throws -> Void\n ) async throws -> LinuxContainer {\n let path = try createContainerRoot(id)\n\n let rootfs = try await unpack(\n image: image,\n destination: path.appendingPathComponent(\"rootfs.ext4\"),\n size: rootfsSizeInBytes\n )\n return try await create(\n id,\n image: image,\n rootfs: rootfs,\n configuration: configuration\n )\n }\n\n /// Returns a new container from the provided image and root filesystem mount.\n /// - Parameters:\n /// - id: The container ID.\n /// - image: The image.\n /// - rootfs: The root filesystem mount pointing to an existing block file.\n public func create(\n _ id: String,\n image: Image,\n rootfs: Mount,\n configuration: (inout LinuxContainer.Configuration) throws -> Void\n ) async throws -> LinuxContainer {\n let imageConfig = try await image.config(for: .current).config\n return try LinuxContainer(\n id,\n rootfs: rootfs,\n vmm: self.vmm\n ) { config in\n if let imageConfig {\n config.process = .init(from: imageConfig)\n }\n if let interface = try self.network?.create(id) {\n config.interfaces = [interface]\n config.dns = .init(nameservers: [interface.gateway!])\n }\n try configuration(&config)\n }\n }\n\n /// Returns an existing container from the provided image and root filesystem mount.\n /// - Parameters:\n /// - id: The container ID.\n /// - image: The image.\n public func get(\n _ id: String,\n image: Image,\n ) async throws -> LinuxContainer {\n let path = containerRoot.appendingPathComponent(id)\n guard FileManager.default.fileExists(atPath: path.absolutePath()) else {\n throw ContainerizationError(.notFound, message: \"\\(id) does not exist\")\n }\n\n let rootfs: Mount = .block(\n format: \"ext4\",\n source: path.appendingPathComponent(\"rootfs.ext4\").absolutePath(),\n destination: \"/\",\n options: []\n )\n\n let imageConfig = try await image.config(for: .current).config\n return try LinuxContainer(\n id,\n rootfs: rootfs,\n vmm: self.vmm\n ) { config in\n if let imageConfig {\n config.process = .init(from: imageConfig)\n }\n if let interface = try self.network?.create(id) {\n config.interfaces = [interface]\n config.dns = .init(nameservers: [interface.gateway!])\n }\n }\n }\n\n /// Performs the cleanup of a container.\n /// - Parameter id: The container ID.\n public func delete(_ id: String) throws {\n try self.network?.release(id)\n let path = containerRoot.appendingPathComponent(id)\n try FileManager.default.removeItem(at: path)\n }\n\n private func createContainerRoot(_ id: String) throws -> URL {\n let path = containerRoot.appendingPathComponent(id)\n try FileManager.default.createDirectory(at: path, withIntermediateDirectories: false)\n return path\n }\n\n private func unpack(image: Image, destination: URL, size: UInt64) async throws -> Mount {\n do {\n let unpacker = EXT4Unpacker(blockSizeInBytes: size)\n return try await unpacker.unpack(image, for: .current, at: destination)\n } catch let err as ContainerizationError {\n if err.code == .exists {\n return .block(\n format: \"ext4\",\n source: destination.absolutePath(),\n destination: \"/\",\n options: []\n )\n }\n throw err\n }\n }\n}\n\nextension CIDRAddress {\n /// The gateway address of the network.\n public var gateway: IPv4Address {\n IPv4Address(fromValue: self.lower.value + 1)\n }\n}\n\n@available(macOS 26.0, *)\nprivate struct SendableReference: Sendable {\n nonisolated(unsafe) private let reference: vmnet_network_ref\n}\n\n#endif\n"], ["/containerization/vminitd/Sources/vminitd/IOPair.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport Synchronization\n\nfinal class IOPair: Sendable {\n let readFrom: IOCloser\n let writeTo: IOCloser\n nonisolated(unsafe) let buffer: UnsafeMutableBufferPointer\n private let logger: Logger?\n\n private let done: Atomic\n\n init(readFrom: IOCloser, writeTo: IOCloser, logger: Logger? = nil) {\n self.readFrom = readFrom\n self.writeTo = writeTo\n self.done = Atomic(false)\n self.buffer = UnsafeMutableBufferPointer.allocate(capacity: Int(getpagesize()))\n self.logger = logger\n }\n\n func relay() throws {\n let readFromFd = self.readFrom.fileDescriptor\n let writeToFd = self.writeTo.fileDescriptor\n\n let readFrom = OSFile(fd: readFromFd)\n let writeTo = OSFile(fd: writeToFd)\n\n try ProcessSupervisor.default.poller.add(readFromFd, mask: EPOLLIN) { mask in\n if mask.isHangup && !mask.readyToRead {\n self.close()\n return\n }\n // Loop so that in the case that someone wrote > buf.count down the pipe\n // we properly will drain it fully.\n while true {\n let r = readFrom.read(self.buffer)\n if r.read > 0 {\n let view = UnsafeMutableBufferPointer(\n start: self.buffer.baseAddress,\n count: r.read\n )\n\n let w = writeTo.write(view)\n if w.wrote != r.read {\n self.logger?.error(\"stopping relay: short write for stdio\")\n self.close()\n return\n }\n }\n\n switch r.action {\n case .error(let errno):\n self.logger?.error(\"failed with errno \\(errno) while reading for fd \\(readFromFd)\")\n fallthrough\n case .eof:\n self.close()\n self.logger?.debug(\"closing relay for \\(readFromFd)\")\n return\n case .again:\n // We read all we could, exit.\n if mask.isHangup {\n self.close()\n }\n return\n default:\n break\n }\n }\n }\n }\n\n func close() {\n guard\n self.done.compareExchange(\n expected: false,\n desired: true,\n successOrdering: .acquiringAndReleasing,\n failureOrdering: .acquiring\n ).exchanged\n else {\n return\n }\n\n self.buffer.deallocate()\n\n let readFromFd = self.readFrom.fileDescriptor\n // Remove the fd from our global epoll instance first.\n do {\n try ProcessSupervisor.default.poller.delete(readFromFd)\n } catch {\n self.logger?.error(\"failed to delete fd from epoll \\(readFromFd): \\(error)\")\n }\n\n do {\n try self.readFrom.close()\n } catch {\n self.logger?.error(\"failed to close reader fd for IOPair: \\(error)\")\n }\n\n do {\n try self.writeTo.close()\n } catch {\n self.logger?.error(\"failed to close writer fd for IOPair: \\(error)\")\n }\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/ProcessSupervisor.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nactor ProcessSupervisor {\n private let queue: DispatchQueue\n // `DispatchSourceSignal` is thread-safe.\n private nonisolated(unsafe) let source: DispatchSourceSignal\n private var processes = [ManagedProcess]()\n\n var log: Logger?\n\n func setLog(_ log: Logger?) {\n self.log = log\n }\n\n static let `default` = ProcessSupervisor()\n\n let poller: Epoll\n\n private init() {\n let queue = DispatchQueue(label: \"process-supervisor\")\n self.source = DispatchSource.makeSignalSource(signal: SIGCHLD, queue: queue)\n self.queue = queue\n self.poller = try! Epoll()\n let t = Thread {\n try! self.poller.run()\n }\n t.start()\n }\n\n func ready() {\n self.source.setEventHandler {\n do {\n self.log?.debug(\"received SIGCHLD, reaping processes\")\n try self.handleSignal()\n } catch {\n self.log?.error(\"reaping processes failed\", metadata: [\"error\": \"\\(error)\"])\n }\n }\n self.source.resume()\n }\n\n private func handleSignal() throws {\n dispatchPrecondition(condition: .onQueue(queue))\n\n self.log?.debug(\"starting to wait4 processes\")\n let exited = Reaper.reap()\n self.log?.debug(\"finished wait4 of \\(exited.count) processes\")\n\n self.log?.debug(\"checking for exit of managed process\", metadata: [\"exits\": \"\\(exited)\", \"processes\": \"\\(processes.count)\"])\n let exitedProcesses = self.processes.filter { proc in\n exited.contains { pid, _ in\n proc.pid == pid\n }\n }\n\n for proc in exitedProcesses {\n let pid = proc.pid\n if pid <= 0 {\n continue\n }\n\n if let status = exited[pid] {\n self.log?.debug(\n \"managed process exited\",\n metadata: [\n \"pid\": \"\\(pid)\",\n \"status\": \"\\(status)\",\n \"count\": \"\\(processes.count - 1)\",\n ])\n proc.setExit(status)\n self.processes.removeAll(where: { $0.pid == pid })\n }\n }\n }\n\n func start(process: ManagedProcess) throws -> Int32 {\n self.log?.debug(\"in supervisor lock to start process\")\n defer {\n self.log?.debug(\"out of supervisor lock to start process\")\n }\n\n do {\n self.processes.append(process)\n return try process.start()\n } catch {\n self.log?.error(\"process start failed \\(error)\", metadata: [\"process-id\": \"\\(process.id)\"])\n throw error\n }\n }\n\n deinit {\n self.log?.info(\"process supervisor deinit\")\n source.cancel()\n }\n}\n"], ["/containerization/Sources/Integration/Suite.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport NIOCore\n\nlet log = {\n LoggingSystem.bootstrap(StreamLogHandler.standardError)\n var log = Logger(label: \"com.apple.containerization\")\n log.logLevel = .debug\n return log\n}()\n\nenum IntegrationError: Swift.Error {\n case assert(msg: String)\n case noOutput\n}\n\nstruct SkipTest: Swift.Error, CustomStringConvertible {\n let reason: String\n\n var description: String {\n reason\n }\n}\n\n@main\nstruct IntegrationSuite: AsyncParsableCommand {\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.containerization\")\n }()\n\n private static let _contentStore: ContentStore = {\n try! LocalContentStore(path: appRoot.appending(path: \"content\"))\n }()\n\n private static let _imageStore: ImageStore = {\n try! ImageStore(\n path: appRoot,\n contentStore: contentStore\n )\n }()\n\n static let _testDir: URL = {\n FileManager.default.uniqueTemporaryDirectory(create: true)\n }()\n\n static var testDir: URL {\n _testDir\n }\n\n static var imageStore: ImageStore {\n _imageStore\n }\n\n static var contentStore: ContentStore {\n _contentStore\n }\n\n static let initImage = \"vminit:latest\"\n\n @Option(name: .shortAndLong, help: \"Path to a log file\")\n var bootlog: String\n\n @Option(name: .shortAndLong, help: \"Path to a kernel binary\")\n var kernel: String = \"./bin/vmlinux\"\n\n static func binPath(name: String) -> URL {\n URL(fileURLWithPath: FileManager.default.currentDirectoryPath)\n .appendingPathComponent(\"bin\")\n .appendingPathComponent(name)\n }\n\n func bootstrap() async throws -> (rootfs: Containerization.Mount, vmm: VirtualMachineManager, image: Containerization.Image) {\n let reference = \"ghcr.io/linuxcontainers/alpine:3.20\"\n let store = Self.imageStore\n\n let initImage = try await store.getInitImage(reference: Self.initImage)\n let initfs = try await {\n let p = Self.binPath(name: \"init.block\")\n do {\n return try await initImage.initBlock(at: p, for: .linuxArm)\n } catch let err as ContainerizationError {\n guard err.code == .exists else {\n throw err\n }\n return .block(\n format: \"ext4\",\n source: p.absolutePath(),\n destination: \"/\",\n options: [\"ro\"]\n )\n }\n }()\n\n var testKernel = Kernel(path: .init(filePath: kernel), platform: .linuxArm)\n testKernel.commandLine.addDebug()\n let image = try await Self.fetchImage(reference: reference, store: store)\n let platform = Platform(arch: \"arm64\", os: \"linux\", variant: \"v8\")\n\n let fs: Containerization.Mount = try await {\n let fsPath = Self.testDir.appending(component: \"rootfs.ext4\")\n do {\n let unpacker = EXT4Unpacker(blockSizeInBytes: 2.gib())\n return try await unpacker.unpack(image, for: platform, at: fsPath)\n } catch let err as ContainerizationError {\n if err.code == .exists {\n return .block(\n format: \"ext4\",\n source: fsPath.absolutePath(),\n destination: \"/\",\n options: []\n )\n }\n throw err\n }\n }()\n\n let clPath = Self.testDir.appending(component: \"rn.ext4\").absolutePath()\n try? FileManager.default.removeItem(atPath: clPath)\n\n let cl = try fs.clone(to: clPath)\n return (\n cl,\n VZVirtualMachineManager(\n kernel: testKernel,\n initialFilesystem: initfs,\n bootlog: bootlog\n ),\n image\n )\n }\n\n static func fetchImage(reference: String, store: ImageStore) async throws -> Containerization.Image {\n do {\n return try await store.get(reference: reference)\n } catch let error as ContainerizationError {\n if error.code == .notFound {\n return try await store.pull(reference: reference)\n }\n throw error\n }\n }\n\n static func adjustLimits() throws {\n var limits = rlimit()\n guard getrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n limits.rlim_cur = 65536\n limits.rlim_max = 65536\n\n guard setrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n }\n\n // Why does this exist?\n //\n // We need the virtualization entitlement to execute these tests.\n // There currently does not exist a straightforward way to do this\n // in a pure swift package.\n //\n // In order to not have a dependency on xcode, we create an executable\n // for our integration tests that can be signed then ran.\n //\n // We also can't import Testing as it expects to be run from a runner.\n // Hopefully this improves over time.\n func run() async throws {\n try Self.adjustLimits()\n let suiteStarted = CFAbsoluteTimeGetCurrent()\n log.info(\"starting integration suite\\n\")\n\n let tests: [String: () async throws -> Void] = [\n \"process true\": testProcessTrue,\n \"process false\": testProcessFalse,\n \"process echo hi\": testProcessEchoHi,\n \"process user\": testProcessUser,\n \"process stdin\": testProcessStdin,\n \"process home envvar\": testProcessHomeEnvvar,\n \"process custom home envvar\": testProcessCustomHomeEnvvar,\n \"process tty ensure TERM\": testProcessTtyEnvvar,\n \"multiple concurrent processes\": testMultipleConcurrentProcesses,\n \"multiple concurrent processes with output stress\": testMultipleConcurrentProcessesOutputStress,\n \"container hostname\": testHostname,\n \"container hosts\": testHostsFile,\n \"container mount\": testMounts,\n \"nested virt\": testNestedVirtualizationEnabled,\n \"container manager\": testContainerManagerCreate,\n ]\n\n var passed = 0\n var skipped = 0\n for (name, test) in tests {\n do {\n log.info(\"test \\(name) started...\")\n\n let started = CFAbsoluteTimeGetCurrent()\n try await test()\n let lasted = CFAbsoluteTimeGetCurrent() - started\n log.info(\"✅ test \\(name) complete in \\(lasted)s.\")\n passed += 1\n } catch let err as SkipTest {\n log.info(\"⏭️ skipped test: \\(err)\")\n skipped += 1\n } catch {\n log.error(\"❌ test \\(name) failed: \\(error)\")\n }\n }\n\n let ended = CFAbsoluteTimeGetCurrent() - suiteStarted\n var finishingText = \"\\n\\nIntegration suite completed in \\(ended)s with \\(passed)/\\(tests.count) passed\"\n if skipped > 0 {\n finishingText += \" and \\(skipped)/\\(tests.count) skipped\"\n }\n finishingText += \"!\"\n\n log.info(\"\\(finishingText)\")\n\n if passed + skipped < tests.count {\n log.error(\"❌\")\n throw ExitCode(1)\n }\n try? FileManager.default.removeItem(at: Self.testDir)\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Command.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CShim\nimport Foundation\nimport Synchronization\n\n#if canImport(Darwin)\nimport Darwin\nprivate let _kill = Darwin.kill\n#elseif canImport(Musl)\nimport Musl\nprivate let _kill = Musl.kill\n#elseif canImport(Glibc)\nimport Glibc\nprivate let _kill = Glibc.kill\n#endif\n\n/// Use a command to run an executable.\npublic struct Command: Sendable {\n /// Path to the executable binary.\n public var executable: String\n /// Arguments provided to the binary.\n public var arguments: [String]\n /// Environment variables for the process.\n public var environment: [String]\n /// The directory where the process should execute.\n public var directory: String?\n /// Additional files to pass to the process.\n public var extraFiles: [FileHandle]\n /// The standard input.\n public var stdin: FileHandle?\n /// The standard output.\n public var stdout: FileHandle?\n /// The standard error.\n public var stderr: FileHandle?\n\n private let state: State\n\n /// System level attributes to set on the process.\n public struct Attrs: Sendable {\n /// Set pgroup for the new process.\n public var setPGroup: Bool\n /// Inherit the real uid/gid of the parent.\n public var resetIDs: Bool\n /// Reset the child's signal handlers to the default.\n public var setSignalDefault: Bool\n /// The initial signal mask for the process.\n public var signalMask: UInt32\n /// Create a new session for the process.\n public var setsid: Bool\n /// Set the controlling terminal for the process to fd 0.\n public var setctty: Bool\n /// Set the process user ID.\n public var uid: UInt32?\n /// Set the process group ID.\n public var gid: UInt32?\n\n public init(\n setPGroup: Bool = false,\n resetIDs: Bool = false,\n setSignalDefault: Bool = true,\n signalMask: UInt32 = 0,\n setsid: Bool = false,\n setctty: Bool = false,\n uid: UInt32? = nil,\n gid: UInt32? = nil\n ) {\n self.setPGroup = setPGroup\n self.resetIDs = resetIDs\n self.setSignalDefault = setSignalDefault\n self.signalMask = signalMask\n self.setsid = setsid\n self.setctty = setctty\n self.uid = uid\n self.gid = gid\n }\n }\n\n private final class State: Sendable {\n let pid: Atomic = Atomic(-1)\n }\n\n /// Attributes to set on the process.\n public var attrs = Attrs()\n\n /// System level process identifier.\n public var pid: Int32 { self.state.pid.load(ordering: .acquiring) }\n\n public init(\n _ executable: String,\n arguments: [String] = [],\n environment: [String] = environment(),\n directory: String? = nil,\n extraFiles: [FileHandle] = []\n ) {\n self.executable = executable\n self.arguments = arguments\n self.environment = environment\n self.extraFiles = extraFiles\n self.directory = directory\n self.state = State()\n }\n\n public static func environment() -> [String] {\n ProcessInfo.processInfo.environment\n .map { \"\\($0)=\\($1)\" }\n }\n}\n\nextension Command {\n public enum Error: Swift.Error, CustomStringConvertible {\n case processRunning\n\n public var description: String {\n switch self {\n case .processRunning:\n return \"the process is already running\"\n }\n }\n }\n}\n\nextension Command {\n @discardableResult\n public func kill(_ signal: Int32) -> Int32? {\n let pid = self.pid\n guard pid > 0 else {\n return nil\n }\n return _kill(pid, signal)\n }\n}\n\nextension Command {\n /// Start the process.\n public func start() throws {\n guard self.pid == -1 else {\n throw Error.processRunning\n }\n let child = try execute()\n self.state.pid.store(child, ordering: .releasing)\n }\n\n /// Wait for the process to exit and return the exit status.\n @discardableResult\n public func wait() throws -> Int32 {\n var rus = rusage()\n var ws = Int32()\n\n let pid = self.pid\n guard pid > 0 else {\n return -1\n }\n\n let result = wait4(pid, &ws, 0, &rus)\n guard result == pid else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n return Self.toExitStatus(ws)\n }\n\n private func execute() throws -> pid_t {\n var attrs = exec_command_attrs()\n exec_command_attrs_init(&attrs)\n\n let set = try createFileset()\n defer {\n try? set.null.close()\n }\n var fds = [Int32](repeating: 0, count: set.handles.count)\n for (i, handle) in set.handles.enumerated() {\n fds[i] = handle.fileDescriptor\n }\n\n attrs.setsid = self.attrs.setsid ? 1 : 0\n attrs.setctty = self.attrs.setctty ? 1 : 0\n attrs.setpgid = self.attrs.setPGroup ? 1 : 0\n\n var cwdPath: UnsafeMutablePointer?\n if let chdir = self.directory {\n cwdPath = strdup(chdir)\n }\n defer {\n if let cwdPath {\n free(cwdPath)\n }\n }\n\n if let uid = self.attrs.uid {\n attrs.uid = uid\n }\n if let gid = self.attrs.gid {\n attrs.gid = gid\n }\n\n var pid: pid_t = 0\n var argv = ([executable] + arguments).map { strdup($0) } + [nil]\n defer {\n for arg in argv where arg != nil {\n free(arg)\n }\n }\n\n let env = environment.map { strdup($0) } + [nil]\n defer {\n for e in env where e != nil {\n free(e)\n }\n }\n\n let result = fds.withUnsafeBufferPointer { file_handles in\n exec_command(\n &pid,\n argv[0],\n &argv,\n env,\n file_handles.baseAddress!, Int32(file_handles.count),\n cwdPath ?? nil,\n &attrs)\n }\n guard result == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n\n return pid\n }\n\n /// Create a posix_spawn file actions set of fds to pass to the new process\n private func createFileset() throws -> (null: FileHandle, handles: [FileHandle]) {\n // grab dev null incase a handle passed by the user is nil\n let null = try openDevNull()\n var files = [FileHandle]()\n files.append(stdin ?? null)\n files.append(stdout ?? null)\n files.append(stderr ?? null)\n files.append(contentsOf: extraFiles)\n return (null: null, handles: files)\n }\n\n /// Returns a file handle to /dev/null.\n private func openDevNull() throws -> FileHandle {\n let fd = open(\"/dev/null\", O_WRONLY, 0)\n guard fd > 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n return FileHandle(fileDescriptor: fd, closeOnDealloc: false)\n }\n}\n\nextension Command {\n private static let signalOffset: Int32 = 128\n\n private static let shift: Int32 = 8\n private static let mask: Int32 = 0x7F\n private static let stopped: Int32 = 0x7F\n private static let exited: Int32 = 0x00\n\n static func signaled(_ ws: Int32) -> Bool {\n ws & mask != stopped && ws & mask != exited\n }\n\n static func exited(_ ws: Int32) -> Bool {\n ws & mask == exited\n }\n\n static func exitStatus(_ ws: Int32) -> Int32 {\n let r: Int32\n #if os(Linux)\n r = ws >> shift & 0xFF\n #else\n r = ws >> shift\n #endif\n return r\n }\n\n public static func toExitStatus(_ ws: Int32) -> Int32 {\n if signaled(ws) {\n // We use the offset as that is how existing container\n // runtimes minic bash for the status when signaled.\n return Int32(Self.signalOffset + ws & mask)\n }\n if exited(ws) {\n return exitStatus(ws)\n }\n return ws\n }\n\n}\n\nprivate func WIFEXITED(_ status: Int32) -> Bool {\n _WSTATUS(status) == 0\n}\n\nprivate func _WSTATUS(_ status: Int32) -> Int32 {\n status & 0x7f\n}\n\nprivate func WIFSIGNALED(_ status: Int32) -> Bool {\n (_WSTATUS(status) != 0) && (_WSTATUS(status) != 0x7f)\n}\n\nprivate func WEXITSTATUS(_ status: Int32) -> Int32 {\n (status >> 8) & 0xff\n}\n\nprivate func WTERMSIG(_ status: Int32) -> Int32 {\n status & 0x7f\n}\n"], ["/containerization/Sources/Containerization/VZVirtualMachine+Helpers.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport Logging\nimport Virtualization\nimport ContainerizationError\n\nextension VZVirtualMachine {\n nonisolated func connect(queue: DispatchQueue, port: UInt32) async throws -> VZVirtioSocketConnection {\n try await withCheckedThrowingContinuation { cont in\n queue.sync {\n guard let vsock = self.socketDevices[0] as? VZVirtioSocketDevice else {\n let error = ContainerizationError(.invalidArgument, message: \"no vsock device\")\n cont.resume(throwing: error)\n return\n }\n vsock.connect(toPort: port) { result in\n switch result {\n case .success(let conn):\n // `conn` isn't used concurrently.\n nonisolated(unsafe) let conn = conn\n cont.resume(returning: conn)\n case .failure(let error):\n cont.resume(throwing: error)\n }\n }\n }\n }\n }\n\n func listen(queue: DispatchQueue, port: UInt32, listener: VZVirtioSocketListener) throws {\n try queue.sync {\n guard let vsock = self.socketDevices[0] as? VZVirtioSocketDevice else {\n throw ContainerizationError(.invalidArgument, message: \"no vsock device\")\n }\n vsock.setSocketListener(listener, forPort: port)\n }\n }\n\n func removeListener(queue: DispatchQueue, port: UInt32) throws {\n try queue.sync {\n guard let vsock = self.socketDevices[0] as? VZVirtioSocketDevice else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"no vsock device to remove\"\n )\n }\n vsock.removeSocketListener(forPort: port)\n }\n }\n\n func start(queue: DispatchQueue) async throws {\n try await withCheckedThrowingContinuation { (cont: CheckedContinuation) in\n queue.sync {\n self.start { result in\n if case .failure(let error) = result {\n cont.resume(throwing: error)\n return\n }\n cont.resume()\n }\n }\n }\n }\n\n func stop(queue: DispatchQueue) async throws {\n try await withCheckedThrowingContinuation { (cont: CheckedContinuation) in\n queue.sync {\n self.stop { error in\n if let error {\n cont.resume(throwing: error)\n return\n }\n cont.resume()\n }\n }\n }\n }\n}\n\nextension VZVirtualMachine {\n func waitForAgent(queue: DispatchQueue) async throws -> FileHandle {\n let agentConnectionRetryCount: Int = 150\n let agentConnectionSleepDuration: Duration = .milliseconds(20)\n\n for _ in 0...agentConnectionRetryCount {\n do {\n return try await self.connect(queue: queue, port: Vminitd.port).dupHandle()\n } catch {\n try await Task.sleep(for: agentConnectionSleepDuration)\n continue\n }\n }\n throw ContainerizationError(.invalidArgument, message: \"no connection to agent socket\")\n }\n}\n\nextension VZVirtioSocketConnection {\n func dupHandle() -> FileHandle {\n let fd = dup(self.fileDescriptor)\n self.close()\n return FileHandle(fileDescriptor: fd, closeOnDealloc: false)\n }\n}\n\n#endif\n"], ["/containerization/Sources/ContainerizationOS/Socket/Socket.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Synchronization\n\n#if canImport(Musl)\nimport Musl\n#elseif canImport(Glibc)\nimport Glibc\n#elseif canImport(Darwin)\nimport Darwin\n#else\n#error(\"Socket not supported on this platform.\")\n#endif\n\n#if !os(Windows)\nlet sysFchmod = fchmod\nlet sysRead = read\nlet sysUnlink = unlink\nlet sysSend = send\nlet sysClose = close\nlet sysShutdown = shutdown\nlet sysBind = bind\nlet sysSocket = socket\nlet sysSetsockopt = setsockopt\nlet sysGetsockopt = getsockopt\nlet sysListen = listen\nlet sysAccept = accept\nlet sysConnect = connect\nlet sysIoctl: @convention(c) (CInt, CUnsignedLong, UnsafeMutableRawPointer) -> CInt = ioctl\n#endif\n\n/// Thread-safe socket wrapper.\npublic final class Socket: Sendable {\n public enum TimeoutOption {\n case send\n case receive\n }\n\n public enum ShutdownOption {\n case read\n case write\n case readWrite\n }\n\n private enum SocketState {\n case created\n case connected\n case listening\n }\n\n private struct State {\n let socketState: SocketState\n let handle: FileHandle?\n let type: SocketType\n let acceptSource: DispatchSourceRead?\n }\n\n private let _closeOnDeinit: Bool\n private let _queue: DispatchQueue\n\n private let state: Mutex\n\n public var fileDescriptor: Int32 {\n guard let handle = state.withLock({ $0.handle }) else {\n return -1\n }\n return handle.fileDescriptor\n }\n\n public convenience init(type: SocketType, closeOnDeinit: Bool = true) throws {\n let sockFD = sysSocket(type.domain, type.type, 0)\n if sockFD < 0 {\n throw SocketError.withErrno(\"failed to create socket: \\(sockFD)\", errno: errno)\n }\n self.init(fd: sockFD, type: type, closeOnDeinit: closeOnDeinit)\n }\n\n init(fd: Int32, type: SocketType, closeOnDeinit: Bool) {\n _queue = DispatchQueue(label: \"com.apple.containerization.socket\")\n _closeOnDeinit = closeOnDeinit\n let state = State(\n socketState: .created,\n handle: FileHandle(fileDescriptor: fd, closeOnDealloc: false),\n type: type,\n acceptSource: nil\n )\n self.state = Mutex(state)\n }\n\n deinit {\n if _closeOnDeinit {\n try? close()\n }\n }\n}\n\nextension Socket {\n static func errnoToError(msg: String) -> SocketError {\n SocketError.withErrno(\"\\(msg) (\\(_errnoString(errno)))\", errno: errno)\n }\n\n public func connect() throws {\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n guard state.withLock({ $0.socketState }) == .created else {\n throw SocketError.invalidOperationOnSocket(\"connect\")\n }\n\n var res: Int32 = 0\n try state.withLock {\n try $0.type.withSockAddr { (ptr, length) in\n res = Syscall.retrying {\n sysConnect(handle.fileDescriptor, ptr, length)\n }\n }\n }\n if res == -1 {\n throw Socket.errnoToError(msg: \"could not connect to socket \\(state.withLock { $0.type })\")\n }\n state.withLock {\n $0 = State(\n socketState: .connected,\n handle: handle,\n type: $0.type,\n acceptSource: $0.acceptSource\n )\n }\n }\n\n public func listen() throws {\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n guard state.withLock({ $0.socketState }) == .created else {\n throw SocketError.invalidOperationOnSocket(\"listen\")\n }\n\n try state.withLock { try $0.type.beforeBind(fd: handle.fileDescriptor) }\n\n var rc: Int32 = 0\n try state.withLock {\n try $0.type.withSockAddr { (ptr, length) in\n rc = sysBind(handle.fileDescriptor, ptr, length)\n }\n }\n if rc < 0 {\n throw Socket.errnoToError(msg: \"could not bind to \\(state.withLock { $0.type })\")\n }\n\n try state.withLock { try $0.type.beforeListen(fd: handle.fileDescriptor) }\n if sysListen(handle.fileDescriptor, SOMAXCONN) < 0 {\n throw Socket.errnoToError(msg: \"listen failed on \\(state.withLock { $0.type })\")\n }\n state.withLock {\n $0 = State(\n socketState: .listening,\n handle: handle,\n type: $0.type,\n acceptSource: $0.acceptSource\n )\n }\n }\n\n public func close() throws {\n // Already closed.\n guard let handle = state.withLock({ $0.handle }) else {\n return\n }\n if let acceptSource = state.withLock({ $0.acceptSource }) {\n acceptSource.cancel()\n }\n try handle.close()\n state.withLock {\n $0 = State(\n socketState: $0.socketState,\n handle: nil,\n type: $0.type,\n acceptSource: nil\n )\n }\n }\n\n public func write(data: any DataProtocol) throws -> Int {\n guard state.withLock({ $0.socketState }) == .connected else {\n throw SocketError.invalidOperationOnSocket(\"write\")\n }\n\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n if data.isEmpty {\n return 0\n }\n\n try handle.write(contentsOf: data)\n return data.count\n }\n\n public func acceptStream(closeOnDeinit: Bool = true) throws -> AsyncThrowingStream {\n guard state.withLock({ $0.socketState }) == .listening else {\n throw SocketError.invalidOperationOnSocket(\"accept\")\n }\n\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n guard state.withLock({ $0.acceptSource }) == nil else {\n throw SocketError.acceptStreamExists\n }\n\n let source = state.withLock {\n let source = DispatchSource.makeReadSource(\n fileDescriptor: handle.fileDescriptor,\n queue: _queue\n )\n $0 = State(\n socketState: $0.socketState,\n handle: handle,\n type: $0.type,\n acceptSource: source\n )\n return source\n }\n\n return AsyncThrowingStream { cont in\n source.setCancelHandler {\n cont.finish()\n }\n source.setEventHandler(handler: {\n if source.data == 0 {\n source.cancel()\n return\n }\n\n do {\n let connection = try self.accept(closeOnDeinit: closeOnDeinit)\n cont.yield(connection)\n } catch SocketError.closed {\n source.cancel()\n } catch {\n cont.yield(with: .failure(error))\n source.cancel()\n }\n })\n source.activate()\n }\n }\n\n public func accept(closeOnDeinit: Bool = true) throws -> Socket {\n guard state.withLock({ $0.socketState }) == .listening else {\n throw SocketError.invalidOperationOnSocket(\"accept\")\n }\n\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n let (clientFD, socketType) = try state.withLock { try $0.type.accept(fd: handle.fileDescriptor) }\n return Socket(\n fd: clientFD,\n type: socketType,\n closeOnDeinit: closeOnDeinit\n )\n }\n\n public func read(buffer: inout Data) throws -> Int {\n guard state.withLock({ $0.socketState }) == .connected else {\n throw SocketError.invalidOperationOnSocket(\"read\")\n }\n\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n var bytesRead = 0\n let bufferSize = buffer.count\n try buffer.withUnsafeMutableBytes { pointer in\n guard let baseAddress = pointer.baseAddress else {\n throw SocketError.missingBaseAddress\n }\n\n bytesRead = Syscall.retrying {\n sysRead(handle.fileDescriptor, baseAddress, bufferSize)\n }\n if bytesRead < 0 {\n throw Socket.errnoToError(msg: \"Error reading from connection\")\n } else if bytesRead == 0 {\n throw SocketError.closed\n }\n }\n return bytesRead\n }\n\n public func shutdown(how: ShutdownOption) throws {\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n var howOpt: Int32 = 0\n switch how {\n case .read:\n howOpt = Int32(SHUT_RD)\n case .write:\n howOpt = Int32(SHUT_WR)\n case .readWrite:\n howOpt = Int32(SHUT_RDWR)\n }\n\n if sysShutdown(handle.fileDescriptor, howOpt) < 0 {\n throw Socket.errnoToError(msg: \"shutdown failed\")\n }\n }\n\n public func setSockOpt(sockOpt: Int32 = 0, ptr: UnsafeRawPointer, stride: UInt32) throws {\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n if setsockopt(handle.fileDescriptor, SOL_SOCKET, sockOpt, ptr, stride) < 0 {\n throw Socket.errnoToError(msg: \"failed to set sockopt\")\n }\n }\n\n public func setTimeout(option: TimeoutOption, seconds: Int) throws {\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n var sockOpt: Int32 = 0\n switch option {\n case .receive:\n sockOpt = SO_RCVTIMEO\n case .send:\n sockOpt = SO_SNDTIMEO\n }\n\n var timer = timeval()\n timer.tv_sec = seconds\n timer.tv_usec = 0\n\n if setsockopt(\n handle.fileDescriptor,\n SOL_SOCKET,\n sockOpt,\n &timer,\n socklen_t(MemoryLayout.size)\n ) < 0 {\n throw Socket.errnoToError(msg: \"failed to set read timeout\")\n }\n }\n\n static func _errnoString(_ err: Int32?) -> String {\n String(validatingCString: strerror(errno)) ?? \"error: \\(errno)\"\n }\n}\n\npublic enum SocketError: Error, Equatable, CustomStringConvertible {\n case closed\n case acceptStreamExists\n case invalidOperationOnSocket(String)\n case missingBaseAddress\n case withErrno(_ msg: String, errno: Int32)\n\n public var description: String {\n switch self {\n case .closed:\n return \"socket: closed\"\n case .acceptStreamExists:\n return \"accept stream already exists\"\n case .invalidOperationOnSocket(let operation):\n return \"socket: invalid operation on socket '\\(operation)'\"\n case .missingBaseAddress:\n return \"socket: missing base address\"\n case .withErrno(let msg, _):\n return \"socket: error \\(msg)\"\n }\n }\n}\n"], ["/containerization/Sources/cctl/RunCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\n\nextension Application {\n struct Run: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"run\",\n abstract: \"Run a container\"\n )\n\n @Option(name: [.customLong(\"image\"), .customShort(\"i\")], help: \"Image reference to base the container on\")\n var imageReference: String = \"docker.io/library/alpine:3.16\"\n\n @Option(name: .long, help: \"id for the container\")\n var id: String = \"cctl\"\n\n @Option(name: [.customLong(\"cpus\"), .customShort(\"c\")], help: \"Number of CPUs to allocate to the container\")\n var cpus: Int = 2\n\n @Option(name: [.customLong(\"memory\"), .customShort(\"m\")], help: \"Amount of memory in megabytes\")\n var memory: UInt64 = 1024\n\n @Option(name: .customLong(\"fs-size\"), help: \"The size to create the block filesystem as\")\n var fsSizeInMB: UInt64 = 2048\n\n @Option(name: .customLong(\"mount\"), help: \"Directory to share into the container (Example: /foo:/bar)\")\n var mounts: [String] = []\n\n @Option(name: .long, help: \"IP address with subnet\")\n var ip: String?\n\n @Option(name: .long, help: \"Gateway address\")\n var gateway: String?\n\n @Option(name: .customLong(\"ns\"), help: \"Nameserver addresses\")\n var nameservers: [String] = []\n\n @Option(\n name: [.customLong(\"kernel\"), .customShort(\"k\")], help: \"Kernel binary path\", completion: .file(),\n transform: { str in\n URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)\n })\n public var kernel: String\n\n @Option(name: .long, help: \"Current working directory\")\n var cwd: String = \"/\"\n\n @Argument var arguments: [String] = [\"/bin/sh\"]\n\n func run() async throws {\n let kernel = Kernel(\n path: URL(fileURLWithPath: kernel),\n platform: .linuxArm\n )\n let manager = try await ContainerManager(\n kernel: kernel,\n initfsReference: \"vminit:latest\",\n )\n let sigwinchStream = AsyncSignalHandler.create(notify: [SIGWINCH])\n\n let current = try Terminal.current\n try current.setraw()\n defer { current.tryReset() }\n\n let container = try await manager.create(\n id,\n reference: imageReference,\n rootfsSizeInBytes: fsSizeInMB.mib()\n ) { config in\n config.cpus = cpus\n config.memoryInBytes = memory.mib()\n config.process.setTerminalIO(terminal: current)\n config.process.arguments = arguments\n config.process.workingDirectory = cwd\n\n for mount in self.mounts {\n let paths = mount.split(separator: \":\")\n if paths.count != 2 {\n throw ContainerizationError(\n .invalidArgument,\n message: \"incorrect mount format detected: \\(mount)\"\n )\n }\n let host = String(paths[0])\n let guest = String(paths[1])\n let czMount = Containerization.Mount.share(\n source: host,\n destination: guest\n )\n config.mounts.append(czMount)\n }\n\n var hosts = Hosts.default\n if let ip {\n guard let gateway else {\n throw ContainerizationError(.invalidArgument, message: \"gateway must be specified\")\n }\n config.interfaces.append(NATInterface(address: ip, gateway: gateway))\n config.dns = .init(nameservers: [gateway])\n if nameservers.count > 0 {\n config.dns = .init(nameservers: nameservers)\n }\n hosts.entries.append(\n Hosts.Entry(\n ipAddress: ip,\n hostnames: [id]\n ))\n }\n config.hosts = hosts\n }\n\n defer {\n try? manager.delete(id)\n }\n\n try await container.create()\n try await container.start()\n\n // Resize the containers pty to the current terminal window.\n try? await container.resize(to: try current.size)\n\n try await withThrowingTaskGroup(of: Void.self) { group in\n group.addTask {\n for await _ in sigwinchStream.signals {\n try await container.resize(to: try current.size)\n }\n }\n\n try await container.wait()\n group.cancelAll()\n\n try await container.stop()\n }\n }\n\n private static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.containerization\")\n }()\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/ArchiveWriter.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CArchive\nimport Foundation\n\n/// A class responsible for writing archives in various formats.\npublic final class ArchiveWriter {\n var underlying: OpaquePointer!\n var delegate: FileArchiveWriterDelegate?\n\n /// Initialize a new `ArchiveWriter` with the given configuration.\n /// This method attempts to initialize an empty archive in memory, failing which it throws a `unableToCreateArchive` error.\n public init(configuration: ArchiveWriterConfiguration) throws {\n // because for some bizarre reason, UTF8 paths won't work unless this process explicitly sets a locale like en_US.UTF-8\n try Self.attemptSetLocales(locales: configuration.locales)\n\n guard let underlying = archive_write_new() else { throw ArchiveError.unableToCreateArchive }\n self.underlying = underlying\n\n try setFormat(configuration.format)\n try addFilter(configuration.filter)\n try setOptions(configuration.options)\n }\n\n /// Initialize a new `ArchiveWriter` with the given configuration and specified delegate.\n private convenience init(configuration: ArchiveWriterConfiguration, delegate: FileArchiveWriterDelegate) throws {\n try self.init(configuration: configuration)\n self.delegate = delegate\n try self.open()\n }\n\n private convenience init(configuration: ArchiveWriterConfiguration, file: URL) throws {\n try self.init(configuration: configuration, delegate: FileArchiveWriterDelegate(url: file))\n }\n\n /// Initialize a new `ArchiveWriter` for writing into the specified file with the given configuration options.\n public convenience init(format: Format, filter: Filter, options: [Options] = [], file: URL) throws {\n try self.init(\n configuration: .init(format: format, filter: filter), delegate: FileArchiveWriterDelegate(url: file))\n }\n\n /// Opens the given file for writing data into\n public func open(file: URL) throws {\n guard let underlying = underlying else { throw ArchiveError.noUnderlyingArchive }\n let res = archive_write_open_filename(underlying, file.path)\n try wrap(res, ArchiveError.unableToOpenArchive, underlying: underlying)\n }\n\n /// Opens the given fd for writing data into\n public func open(fileDescriptor: Int32) throws {\n guard let underlying = underlying else { throw ArchiveError.noUnderlyingArchive }\n let res = archive_write_open_fd(underlying, fileDescriptor)\n try wrap(res, ArchiveError.unableToOpenArchive, underlying: underlying)\n }\n\n /// Performs any necessary finalizations on the archive and releases resources.\n public func finishEncoding() throws {\n if let u = underlying {\n let r = archive_free(u)\n do {\n try wrap(r, ArchiveError.unableToCloseArchive, underlying: underlying)\n underlying = nil\n } catch {\n underlying = nil\n throw error\n }\n }\n }\n\n deinit {\n if let u = underlying {\n archive_free(u)\n underlying = nil\n }\n }\n\n private static func attemptSetLocales(locales: [String]) throws {\n for locale in locales {\n if setlocale(LC_ALL, locale) != nil {\n return\n }\n }\n throw ArchiveError.failedToSetLocale(locales: locales)\n }\n}\n\nextension ArchiveWriter {\n fileprivate func open() throws {\n guard let underlying = underlying else { throw ArchiveError.noUnderlyingArchive }\n // TODO: to be or not to be retained, that is the question\n let pointerToSelf = Unmanaged.passUnretained(self).toOpaque()\n\n let res = archive_write_open2(\n underlying,\n pointerToSelf,\n /// The open callback is invoked by archive_write_open(). It should return ARCHIVE_OK if the underlying file or data source is successfully opened. If the open fails, it should call archive_set_error() to register an error code and message and return ARCHIVE_FATAL. Please note that\n /// if open fails, close is not called and resources must be freed inside the open callback or with the free callback.\n { underlying, pointerToSelf in\n do {\n guard let pointerToSelf = pointerToSelf else {\n throw ArchiveError.noArchiveInCallback\n }\n let archive: ArchiveWriter = Unmanaged.fromOpaque(pointerToSelf).takeUnretainedValue()\n guard let delegate = archive.delegate else {\n throw ArchiveError.noDelegateConfigured\n }\n try delegate.open(archive: archive)\n return ARCHIVE_OK\n } catch {\n archive_set_error_wrapper(underlying, ARCHIVE_FATAL, \"\\(error)\")\n return ARCHIVE_FATAL\n }\n },\n /// The write callback is invoked whenever the library needs to write raw bytes to the archive. For correct blocking, each call to the write callback function should translate into a single write(2) system call. This is especially critical when writing archives to tape drives. On\n /// success, the write callback should return the number of bytes actually written. On error, the callback should invoke archive_set_error() to register an error code and message and return -1.\n { underlying, pointerToSelf, dataPointer, count in\n do {\n guard let pointerToSelf = pointerToSelf else {\n throw ArchiveError.noArchiveInCallback\n }\n let archive: ArchiveWriter = Unmanaged.fromOpaque(pointerToSelf).takeUnretainedValue()\n guard let delegate = archive.delegate else {\n throw ArchiveError.noDelegateConfigured\n }\n return try delegate.write(\n archive: archive, buffer: UnsafeRawBufferPointer(start: dataPointer, count: count))\n } catch {\n archive_set_error_wrapper(underlying, ARCHIVE_FATAL, \"\\(error)\")\n return -1\n }\n },\n /// The close callback is invoked by archive_close when the archive processing is complete. If the open callback fails, the close callback is not invoked. The callback should return ARCHIVE_OK on success. On failure, the callback should invoke archive_set_error() to register an\n /// error code and message and return\n { underlying, pointerToSelf in\n do {\n guard let pointerToSelf = pointerToSelf else {\n throw ArchiveError.noArchiveInCallback\n }\n let archive: ArchiveWriter = Unmanaged.fromOpaque(pointerToSelf).takeUnretainedValue()\n guard let delegate = archive.delegate else {\n throw ArchiveError.noDelegateConfigured\n }\n try delegate.close(archive: archive)\n return ARCHIVE_OK\n } catch {\n archive_set_error_wrapper(underlying, ARCHIVE_FATAL, \"\\(error)\")\n return ARCHIVE_FATAL\n }\n },\n /// The free callback is always invoked on archive_free. The return code of this callback is not processed.\n { underlying, pointerToSelf in\n do {\n guard let pointerToSelf = pointerToSelf else {\n throw ArchiveError.noArchiveInCallback\n }\n let archive: ArchiveWriter = Unmanaged.fromOpaque(pointerToSelf).takeUnretainedValue()\n guard let delegate = archive.delegate else {\n throw ArchiveError.noDelegateConfigured\n }\n delegate.free(archive: archive)\n\n // TODO: should we balance the Unmanaged refcount here? Need to test for leaks.\n return ARCHIVE_OK\n } catch {\n archive_set_error_wrapper(underlying, ARCHIVE_FATAL, \"\\(error)\")\n return ARCHIVE_FATAL\n }\n }\n )\n\n try wrap(res, ArchiveError.unableToOpenArchive, underlying: underlying)\n }\n}\n\npublic class ArchiveWriterTransaction {\n private let writer: ArchiveWriter\n\n fileprivate init(writer: ArchiveWriter) {\n self.writer = writer\n }\n\n public func writeHeader(entry: WriteEntry) throws {\n try writer.writeHeader(entry: entry)\n }\n\n public func writeChunk(data: UnsafeRawBufferPointer) throws {\n try writer.writeData(data: data)\n }\n\n public func finish() throws {\n try writer.finishEntry()\n }\n}\n\nextension ArchiveWriter {\n public func makeTransactionWriter() -> ArchiveWriterTransaction {\n ArchiveWriterTransaction(writer: self)\n }\n\n /// Create a new entry in the archive with the given properties.\n /// - Parameters:\n /// - entry: A `WriteEntry` object describing the metadata of the entry to be created\n /// (e.g., name, modification date, permissions).\n /// - data: The `Data` object containing the content for the new entry.\n public func writeEntry(entry: WriteEntry, data: Data) throws {\n try data.withUnsafeBytes { bytes in\n try writeEntry(entry: entry, data: bytes)\n }\n }\n\n /// Creates a new entry in the archive with the given properties.\n ///\n /// This method performs the following:\n /// 1. Writes the archive header using the provided `WriteEntry` metadata.\n /// 2. Writes the content from the `UnsafeRawBufferPointer` into the archive.\n /// 3. Finalizes the entry in the archive.\n ///\n /// - Parameters:\n /// - entry: A `WriteEntry` object describing the metadata of the entry to be created\n /// (e.g., name, modification date, permissions, type).\n /// - data: An optional `UnsafeRawBufferPointer` containing the raw bytes for the new entry's\n /// content. Pass `nil` for entries that do not have content data (e.g., directories, symlinks).\n public func writeEntry(entry: WriteEntry, data: UnsafeRawBufferPointer?) throws {\n try writeHeader(entry: entry)\n if let data = data {\n try writeData(data: data)\n }\n try finishEntry()\n }\n\n fileprivate func writeHeader(entry: WriteEntry) throws {\n guard let underlying = self.underlying else { throw ArchiveError.noUnderlyingArchive }\n\n try wrap(\n archive_write_header(underlying, entry.underlying), ArchiveError.unableToWriteEntryHeader,\n underlying: underlying)\n }\n\n fileprivate func finishEntry() throws {\n guard let underlying = self.underlying else { throw ArchiveError.noUnderlyingArchive }\n\n archive_write_finish_entry(underlying)\n }\n\n fileprivate func writeData(data: UnsafeRawBufferPointer) throws {\n guard let underlying = self.underlying else { throw ArchiveError.noUnderlyingArchive }\n\n let result = archive_write_data(underlying, data.baseAddress, data.count)\n guard result >= 0 else {\n throw ArchiveError.unableToWriteData(result)\n }\n }\n}\n\nextension ArchiveWriter {\n /// Recursively archives the content of a directory. Regular files, symlinks and directories are added into the archive.\n /// Note: Symlinks are added to the archive if both the source and target for the symlink are both contained in the top level directory.\n public func archiveDirectory(_ dir: URL) throws {\n let fm = FileManager.default\n let resourceKeys = Set([\n .fileSizeKey, .fileResourceTypeKey,\n .creationDateKey, .contentAccessDateKey, .contentModificationDateKey, .fileSecurityKey,\n ])\n guard let directoryEnumerator = fm.enumerator(at: dir, includingPropertiesForKeys: Array(resourceKeys), options: .producesRelativePathURLs) else {\n throw POSIXError(.ENOTDIR)\n }\n for case let fileURL as URL in directoryEnumerator {\n var mode = mode_t()\n var uid = uid_t()\n var gid = gid_t()\n let resourceValues = try fileURL.resourceValues(forKeys: resourceKeys)\n guard let type = resourceValues.fileResourceType else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .fileResourceTypeKey)\n }\n let allowedTypes: [URLFileResourceType] = [.directory, .regular, .symbolicLink]\n guard allowedTypes.contains(type) else {\n continue\n }\n var size: Int64 = 0\n let entry = WriteEntry()\n if type == .regular {\n guard let _size = resourceValues.fileSize else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .fileSizeKey)\n }\n size = Int64(_size)\n } else if type == .symbolicLink {\n let target = fileURL.resolvingSymlinksInPath().absoluteString\n let root = dir.absoluteString\n guard target.hasPrefix(root) else {\n continue\n }\n let linkTarget = target.dropFirst(root.count + 1)\n entry.symlinkTarget = String(linkTarget)\n }\n\n guard let created = resourceValues.creationDate else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .creationDateKey)\n }\n guard let access = resourceValues.contentAccessDate else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .contentAccessDateKey)\n }\n guard let modified = resourceValues.contentModificationDate else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .contentModificationDateKey)\n }\n guard let perms = resourceValues.fileSecurity else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .fileSecurityKey)\n }\n CFFileSecurityGetMode(perms, &mode)\n CFFileSecurityGetOwner(perms, &uid)\n CFFileSecurityGetGroup(perms, &gid)\n entry.path = fileURL.relativePath\n entry.size = size\n entry.creationDate = created\n entry.modificationDate = modified\n entry.contentAccessDate = access\n entry.fileType = type\n entry.group = gid\n entry.owner = uid\n entry.permissions = mode\n if type == .regular {\n let p = dir.appending(path: fileURL.relativePath)\n let data = try Data(contentsOf: p, options: .uncached)\n try self.writeEntry(entry: entry, data: data)\n } else {\n try self.writeHeader(entry: entry)\n }\n }\n }\n}\n"], ["/containerization/Sources/Containerization/Image/ImageStore/ImageStore+Export.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationIO\nimport ContainerizationOCI\nimport Crypto\nimport Foundation\n\nextension ImageStore {\n internal struct ExportOperation {\n let name: String\n let tag: String\n let contentStore: ContentStore\n let client: ContentClient\n let progress: ProgressHandler?\n\n init(name: String, tag: String, contentStore: ContentStore, client: ContentClient, progress: ProgressHandler? = nil) {\n self.contentStore = contentStore\n self.client = client\n self.progress = progress\n self.name = name\n self.tag = tag\n }\n\n @discardableResult\n internal func export(index: Descriptor, platforms: (Platform) -> Bool) async throws -> Descriptor {\n var pushQueue: [[Descriptor]] = []\n var current: [Descriptor] = [index]\n while !current.isEmpty {\n let children = try await self.getChildren(descs: current)\n let matches = try filterPlatforms(matcher: platforms, children).uniqued { $0.digest }\n pushQueue.append(matches)\n current = matches\n }\n let localIndexData = try await self.createIndex(from: index, matching: platforms)\n\n await updatePushProgress(pushQueue: pushQueue, localIndexData: localIndexData)\n\n // We need to work bottom up when pushing an image.\n // First, the tar blobs / config layers, then, the manifests and so on...\n // When processing a given \"level\", the requests maybe made in parallel.\n // We need to ensure that the child level has been uploaded fully\n // before uploading the parent level.\n try await withThrowingTaskGroup(of: Void.self) { group in\n for layerGroup in pushQueue.reversed() {\n for chunk in layerGroup.chunks(ofCount: 8) {\n for desc in chunk {\n guard let content = try await self.contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(desc.digest)\")\n }\n group.addTask {\n let readStream = try ReadStream(url: content.path)\n try await self.pushContent(descriptor: desc, stream: readStream)\n }\n }\n try await group.waitForAll()\n }\n }\n }\n\n // Lastly, we need to construct and push a new index, since we may\n // have pushed content only for specific platforms.\n let digest = SHA256.hash(data: localIndexData)\n let descriptor = Descriptor(\n mediaType: MediaTypes.index,\n digest: digest.digestString,\n size: Int64(localIndexData.count))\n let stream = ReadStream(data: localIndexData)\n try await self.pushContent(descriptor: descriptor, stream: stream)\n return descriptor\n }\n\n private func updatePushProgress(pushQueue: [[Descriptor]], localIndexData: Data) async {\n for layerGroup in pushQueue {\n for desc in layerGroup {\n await progress?([\n ProgressEvent(event: \"add-total-size\", value: desc.size),\n ProgressEvent(event: \"add-total-items\", value: 1),\n ])\n }\n }\n await progress?([\n ProgressEvent(event: \"add-total-size\", value: localIndexData.count),\n ProgressEvent(event: \"add-total-items\", value: 1),\n ])\n }\n\n private func createIndex(from index: Descriptor, matching: (Platform) -> Bool) async throws -> Data {\n guard let content = try await self.contentStore.get(digest: index.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(index.digest)\")\n }\n var idx: Index = try content.decode()\n let manifests = idx.manifests\n var matchedManifests: [Descriptor] = []\n var skippedPlatforms = false\n for manifest in manifests {\n guard let p = manifest.platform else {\n continue\n }\n if matching(p) {\n matchedManifests.append(manifest)\n } else {\n skippedPlatforms = true\n }\n }\n if !skippedPlatforms {\n return try content.data()\n }\n idx.manifests = matchedManifests\n return try JSONEncoder().encode(idx)\n }\n\n private func pushContent(descriptor: Descriptor, stream: ReadStream) async throws {\n do {\n let generator = {\n try stream.reset()\n return stream.stream\n }\n try await client.push(name: name, ref: tag, descriptor: descriptor, streamGenerator: generator, progress: progress)\n await progress?([\n ProgressEvent(event: \"add-size\", value: descriptor.size),\n ProgressEvent(event: \"add-items\", value: 1),\n ])\n } catch let err as ContainerizationError {\n guard err.code != .exists else {\n // We reported the total items and size and have to account for them in existing content.\n await progress?([\n ProgressEvent(event: \"add-size\", value: descriptor.size),\n ProgressEvent(event: \"add-items\", value: 1),\n ])\n return\n }\n throw err\n }\n }\n\n private func getChildren(descs: [Descriptor]) async throws -> [Descriptor] {\n var out: [Descriptor] = []\n for desc in descs {\n let mediaType = desc.mediaType\n guard let content = try await self.contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(desc.digest)\")\n }\n switch mediaType {\n case MediaTypes.index, MediaTypes.dockerManifestList:\n let index: Index = try content.decode()\n out.append(contentsOf: index.manifests)\n case MediaTypes.imageManifest, MediaTypes.dockerManifest:\n let manifest: Manifest = try content.decode()\n out.append(manifest.config)\n out.append(contentsOf: manifest.layers)\n default:\n continue\n }\n }\n return out\n }\n }\n}\n"], ["/containerization/vminitd/Sources/vmexec/RunCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerizationOCI\nimport Foundation\nimport LCShim\nimport Logging\nimport Musl\n\nstruct RunCommand: ParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"run\",\n abstract: \"Run a container\"\n )\n\n @Option(name: .long, help: \"path to an OCI bundle\")\n var bundlePath: String\n\n mutating func run() throws {\n LoggingSystem.bootstrap(App.standardError)\n let log = Logger(label: \"vmexec\")\n\n let bundle = try ContainerizationOCI.Bundle.load(path: URL(filePath: bundlePath))\n let ociSpec = try bundle.loadConfig()\n try execInNamespace(spec: ociSpec, log: log)\n }\n\n private func childRootSetup(rootfs: ContainerizationOCI.Root, mounts: [ContainerizationOCI.Mount], log: Logger) throws {\n // setup rootfs\n try prepareRoot(rootfs: rootfs.path)\n try mountRootfs(rootfs: rootfs.path, mounts: mounts)\n try setDevSymlinks(rootfs: rootfs.path)\n\n try pivotRoot(rootfs: rootfs.path)\n try reOpenDevNull()\n }\n\n private func execInNamespace(spec: ContainerizationOCI.Spec, log: Logger) throws {\n guard let process = spec.process else {\n fatalError(\"no process configuration found in runtime spec\")\n }\n guard let root = spec.root else {\n fatalError(\"no root found in runtime spec\")\n }\n\n let syncfd = FileHandle(fileDescriptor: 3)\n if fcntl(3, F_SETFD, FD_CLOEXEC) == -1 {\n throw App.Errno(stage: \"cloexec(syncfd)\")\n }\n\n guard unshare(CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWUTS) == 0 else {\n throw App.Errno(stage: \"unshare(pid|mnt|uts)\")\n }\n\n let childPipe = Pipe()\n try childPipe.setCloexec()\n let processID = fork()\n\n guard processID != -1 else {\n try? childPipe.fileHandleForReading.close()\n try? childPipe.fileHandleForWriting.close()\n try? syncfd.close()\n\n throw App.Errno(stage: \"fork\")\n }\n\n if processID == 0 { // child\n try childPipe.fileHandleForReading.close()\n try syncfd.close()\n\n guard unshare(CLONE_NEWCGROUP) == 0 else {\n throw App.Errno(stage: \"unshare(cgroup)\")\n }\n\n guard setsid() != -1 else {\n throw App.Errno(stage: \"setsid()\")\n }\n\n try childRootSetup(rootfs: root, mounts: spec.mounts, log: log)\n\n if !spec.hostname.isEmpty {\n let errCode = spec.hostname.withCString { ptr in\n Musl.sethostname(ptr, spec.hostname.count)\n }\n guard errCode == 0 else {\n throw App.Errno(stage: \"sethostname()\")\n }\n }\n\n // Apply O_CLOEXEC to all file descriptors except stdio.\n // This ensures that all unwanted fds we may have accidentally\n // inherited are marked close-on-exec so they stay out of the\n // container.\n try App.applyCloseExecOnFDs()\n\n try App.setRLimits(rlimits: process.rlimits)\n\n // Change stdio to be owned by the requested user.\n try App.fixStdioPerms(user: process.user)\n\n // Set uid, gid, and supplementary groups.\n try App.setPermissions(user: process.user)\n\n if process.terminal {\n guard ioctl(0, UInt(TIOCSCTTY), 0) != -1 else {\n throw App.Errno(stage: \"setctty()\")\n }\n }\n\n try App.exec(process: process)\n } else { // parent process\n try childPipe.fileHandleForWriting.close()\n\n // wait until the pipe is closed then carry on.\n _ = try childPipe.fileHandleForReading.readToEnd()\n try childPipe.fileHandleForReading.close()\n\n // send our child's pid to our parent before we exit.\n var childPid = processID\n let data = Data(bytes: &childPid, count: MemoryLayout.size(ofValue: childPid))\n\n try syncfd.write(contentsOf: data)\n try syncfd.close()\n }\n }\n\n private func mountRootfs(rootfs: String, mounts: [ContainerizationOCI.Mount]) throws {\n let containerMount = ContainerMount(rootfs: rootfs, mounts: mounts)\n try containerMount.mountToRootfs()\n try containerMount.configureConsole()\n }\n\n private func prepareRoot(rootfs: String) throws {\n guard mount(\"\", \"/\", \"\", UInt(MS_SLAVE | MS_REC), nil) == 0 else {\n throw App.Errno(stage: \"mount(slave|rec)\")\n }\n\n guard mount(rootfs, rootfs, \"bind\", UInt(MS_BIND | MS_REC), nil) == 0 else {\n throw App.Errno(stage: \"mount(bind|rec)\")\n }\n }\n\n private func setDevSymlinks(rootfs: String) throws {\n let links: [(src: String, dst: String)] = [\n (\"/proc/self/fd\", \"/dev/fd\"),\n (\"/proc/self/fd/0\", \"/dev/stdin\"),\n (\"/proc/self/fd/1\", \"/dev/stdout\"),\n (\"/proc/self/fd/2\", \"/dev/stderr\"),\n ]\n\n let rootfsURL = URL(fileURLWithPath: rootfs)\n for (src, dst) in links {\n let dest = rootfsURL.appendingPathComponent(dst)\n guard symlink(src, dest.path) == 0 else {\n if errno == EEXIST {\n continue\n }\n throw App.Errno(stage: \"symlink()\")\n }\n }\n }\n\n private func reOpenDevNull() throws {\n let file = open(\"/dev/null\", O_RDWR)\n guard file != -1 else {\n throw App.Errno(stage: \"open(/dev/null)\")\n }\n defer { close(file) }\n\n var devNullStat = stat()\n try withUnsafeMutablePointer(to: &devNullStat) { pointer in\n guard fstat(file, pointer) == 0 else {\n throw App.Errno(stage: \"fstat(/dev/null)\")\n }\n }\n\n for fd: Int32 in 0...2 {\n var fdStat = stat()\n try withUnsafeMutablePointer(to: &fdStat) { pointer in\n guard fstat(fd, pointer) == 0 else {\n throw App.Errno(stage: \"fstat(fd)\")\n }\n }\n\n if fdStat.st_rdev == devNullStat.st_rdev {\n guard dup3(file, fd, 0) != -1 else {\n throw App.Errno(stage: \"dup3(null)\")\n }\n }\n }\n }\n\n /// Pivots the rootfs of the calling process in the namespace to the provided\n /// rootfs in the argument.\n ///\n /// The pivot_root(\".\", \".\") and unmount old root approach is exactly the same\n /// as runc's pivot root implementation in:\n /// https://github.com/opencontainers/runc/blob/main/libcontainer/rootfs_linux.go\n private func pivotRoot(rootfs: String) throws {\n let oldRoot = open(\"/\", O_RDONLY | O_DIRECTORY)\n if oldRoot <= 0 {\n throw App.Errno(stage: \"open(oldroot)\")\n }\n defer { close(oldRoot) }\n\n let newRoot = open(rootfs, O_RDONLY | O_DIRECTORY)\n if newRoot <= 0 {\n throw App.Errno(stage: \"open(newroot)\")\n }\n\n defer { close(newRoot) }\n\n // change cwd to the new root\n guard fchdir(newRoot) == 0 else {\n throw App.Errno(stage: \"fchdir(newroot)\")\n }\n guard CZ_pivot_root(toCString(\".\"), toCString(\".\")) == 0 else {\n throw App.Errno(stage: \"pivot_root()\")\n }\n // change cwd to the old root\n guard fchdir(oldRoot) == 0 else {\n throw App.Errno(stage: \"fchdir(oldroot)\")\n }\n // mount old root rslave so that unmount doesn't propagate back to outside\n // the namespace\n guard mount(\"\", \".\", \"\", UInt(MS_SLAVE | MS_REC), nil) == 0 else {\n throw App.Errno(stage: \"mount(., slave|rec)\")\n }\n // unmount old root\n guard umount2(\".\", Int32(MNT_DETACH)) == 0 else {\n throw App.Errno(stage: \"umount(.)\")\n }\n // switch cwd to the new root\n guard chdir(\"/\") == 0 else {\n throw App.Errno(stage: \"chdir(/)\")\n }\n }\n\n private func toCString(_ str: String) -> UnsafeMutablePointer? {\n let cString = str.utf8CString\n let cStringCopy = UnsafeMutableBufferPointer.allocate(capacity: cString.count)\n _ = cStringCopy.initialize(from: cString)\n return UnsafeMutablePointer(cStringCopy.baseAddress)\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Formatter.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// swiftlint: disable discouraged_direct_init shorthand_operator syntactic_sugar\n\nimport ContainerizationOS\nimport Foundation\nimport SystemPackage\n\nextension EXT4 {\n /// The `EXT4.Formatter` class provides methods to format a block device with the ext4 filesystem.\n /// It allows customization of block size and maximum disk size.\n public class Formatter {\n private let blockSize: UInt32\n private var size: UInt64\n private let groupDescriptorSize: UInt32 = 32\n\n private var blocksPerGroup: UInt32 {\n blockSize * 8\n }\n\n private var maxInodesPerGroup: UInt32 {\n blockSize * 8 // limited by inode bitmap\n }\n\n private var groupsPerDescriptorBlock: UInt32 {\n blockSize / groupDescriptorSize\n }\n\n private var blockCount: UInt32 {\n ((size - 1) / blockSize) + 1\n }\n\n private var groupCount: UInt32 {\n (blockCount - 1) / blocksPerGroup + 1\n }\n\n private var groupDescriptorBlocks: UInt32 {\n ((groupCount - 1) / groupsPerDescriptorBlock + 1) * 32\n }\n\n /// Initializes an ext4 filesystem formatter.\n ///\n /// This constructor creates an instance of the ext4 formatter designed to format a block device\n /// with the ext4 filesystem. The formatter takes the path to the destination block device and\n /// the desired block size of the filesystem as parameters.\n ///\n /// - Parameters:\n /// - devicePath: The path to the block device where the ext4 filesystem will be created.\n /// - blockSize: The block size of the ext4 filesystem, specified in bytes. Common values are\n /// 4096 (4KB) or 1024 (1KB). Default is 4096 (4KB)\n /// - minDiskSize: The minimum disk size required for the formatted filesystem.\n ///\n /// - Note: This ext4 formatter is designed for creating block devices out of container images and does not support all the\n /// features and options available in the full ext4 filesystem implementation. It focuses\n /// on the core functionality required for formatting a block device with ext4.\n ///\n /// - Important: Ensure that the destination block device is accessible and has sufficient permissions\n /// for formatting. The formatting process will erase all existing data on the device.\n public init(_ devicePath: FilePath, blockSize: UInt32 = 4096, minDiskSize: UInt64 = 256.kib()) throws {\n /// The constructor performs the following steps:\n ///\n /// 1. Creates the first 10 inodes:\n /// - Inode 2 is reserved for the root directory ('/').\n /// - Inodes 1 and 3-10 are reserved for other special purposes.\n ///\n /// 2. Marks inode 11 as the first inode available for consumption by files, directories, sockets,\n /// FIFOs, etc.\n ///\n /// 3. Initializes a directory tree with the root directory pointing to inode 2.\n ///\n /// 4. Moves the file descriptor to the start of the block where file metadata and data can be\n /// written, which is located past the filesystem superblocks and group descriptor blocks.\n ///\n /// 5. Creates a \"/lost+found\" directory to satisfy the requirements of e2fsck (ext2/3/4 filesystem\n /// checker).\n\n if !FileManager.default.fileExists(atPath: devicePath.description) {\n FileManager.default.createFile(atPath: devicePath.description, contents: nil)\n }\n guard let fileHandle = FileHandle(forWritingTo: devicePath) else {\n throw Error.notFound(devicePath)\n }\n self.handle = fileHandle\n self.blockSize = blockSize\n self.size = minDiskSize\n // make this a 0 byte file\n guard ftruncate(self.handle.fileDescriptor, 0) == 0 else {\n throw Error.cannotTruncateFile(devicePath)\n }\n // make it a sparse file\n guard lseek(self.handle.fileDescriptor, off_t(self.size - 1), 0) == self.size - 1 else {\n throw Error.cannotCreateSparseFile(devicePath)\n }\n let zero: [UInt8] = [0]\n try self.handle.write(contentsOf: zero)\n // step #1\n self.inodes = [\n Ptr.allocate(capacity: 1), // defective block inode\n {\n let root = Inode.Root()\n let rootPtr = Ptr.allocate(capacity: 1)\n rootPtr.initialize(to: root)\n return rootPtr\n }(),\n ]\n // reserved inodes\n for _ in 2...allocate(capacity: 1))\n }\n // step #2\n self.tree = FileTree(EXT4.RootInode, \"/\")\n // skip past the superblock and block descriptor table\n try self.seek(block: self.groupDescriptorBlocks + 1)\n // lost+found directory is required for e2fsck to pass\n try self.create(path: FilePath(\"/lost+found\"), mode: Inode.Mode(.S_IFDIR, 0o700))\n }\n\n // Creates a hard link at the path specified by `link` that points to the same file or directory as the path specified by `target`.\n //\n // A hard link is a directory entry that points to the same inode as another directory entry. It allows multiple paths to refer to the same file on the file system.\n //\n // - `link`: The path at which to create the new hard link.\n // - `target`: The path of the existing file or directory to which the hard link should point.\n //\n // Throws an error if `target` path does not exist, or `target` is a directory.\n public func link(\n link: FilePath,\n target: FilePath\n ) throws {\n // ensure that target exists\n guard let targetPtr = self.tree.lookup(path: target) else {\n throw Error.notFound(target)\n }\n let targetNode = targetPtr.pointee\n let targetInodePtr = self.inodes[Int(targetNode.inode) - 1]\n var targetInode = targetInodePtr.pointee\n // ensure that target is not a directory since hardlinks cannot be\n // created to directories\n if targetInode.mode.isDir() {\n throw Error.cannotCreateHardlinksToDirTarget(link)\n }\n targetInode.linksCount += 1\n targetInodePtr.initialize(to: targetInode)\n let parentPath: FilePath = link.dir\n if self.tree.lookup(path: link) != nil {\n try self.unlink(path: link)\n }\n guard let parentTreeNodePtr = self.tree.lookup(path: parentPath) else {\n throw Error.notFound(parentPath)\n }\n let parentTreeNode = parentTreeNodePtr.pointee\n let parentInodePtr = self.inodes[Int(parentTreeNode.inode) - 1]\n let parentInode = parentInodePtr.pointee\n guard parentInode.linksCount < EXT4.MaxLinks else {\n throw Error.maximumLinksExceeded(parentPath)\n }\n let linkTreeNodePtr = Ptr.allocate(capacity: 1)\n let linkTreeNode = FileTree.FileTreeNode(\n inode: InodeNumber(2), // this field is ignored, using 2 so array operations dont panic\n name: link.base,\n parent: parentTreeNodePtr,\n children: [],\n blocks: nil,\n link: targetNode.inode\n )\n linkTreeNodePtr.initialize(to: linkTreeNode)\n parentTreeNode.children.append(linkTreeNodePtr)\n parentTreeNodePtr.initialize(to: parentTreeNode)\n }\n\n // Deletes the file or directory at the specified path from the filesystem.\n //\n // It performs the following actions\n // - set link count of the file's inode to 0\n // - recursively set link count to 0 for its children\n // - free the inode\n // - free data blocks\n // - remove directory entry\n //\n // - `path`: The `FilePath` specifying the path of the file or directory to delete.\n public func unlink(path: FilePath, directoryWhiteout: Bool = false) throws {\n guard let pathPtr = self.tree.lookup(path: path) else {\n // We are being asked to unlink something that does not exist. Ignore\n return\n }\n let pathNode = pathPtr.pointee\n let inodeNumber = Int(pathNode.inode) - 1\n let pathInodePtr = self.inodes[inodeNumber]\n var pathInode = pathInodePtr.pointee\n\n if directoryWhiteout && !pathInode.mode.isDir() {\n throw Error.notDirectory(path)\n }\n\n for childPtr in pathNode.children {\n try self.unlink(path: path.join(childPtr.pointee.name))\n }\n\n guard !directoryWhiteout else {\n return\n }\n\n if let parentNodePtr = self.tree.lookup(path: path.dir) {\n let parentNode = parentNodePtr.pointee\n let parentInodePtr = self.inodes[Int(parentNode.inode) - 1]\n var parentInode = parentInodePtr.pointee\n if pathInode.mode.isDir() {\n if parentInode.linksCount > 2 {\n parentInode.linksCount -= 1\n }\n }\n parentInodePtr.initialize(to: parentInode)\n parentNode.children.removeAll { childPtr in\n childPtr.pointee.name == path.base\n }\n parentNodePtr.initialize(to: parentNode)\n }\n\n if let hardlink = pathNode.link {\n // the file we are deleting is a hardlink, decrement the link count\n let linkedInodePtr = self.inodes[Int(hardlink - 1)]\n var linkedInode = linkedInodePtr.pointee\n if linkedInode.linksCount > 2 {\n linkedInode.linksCount -= 1\n linkedInodePtr.initialize(to: linkedInode)\n }\n }\n\n guard inodeNumber > FirstInode else {\n // Free the inodes and the blocks related to the inode only if its valid\n return\n }\n if let blocks = pathNode.blocks {\n if !(blocks.start == blocks.end) {\n self.deletedBlocks.append((start: blocks.start, end: blocks.end))\n }\n }\n for block in pathNode.additionalBlocks ?? [] {\n self.deletedBlocks.append((start: block.start, end: block.end))\n }\n let now = Date().fs()\n pathInode = Inode()\n pathInode.dtime = now.lo\n pathInodePtr.initialize(to: pathInode)\n }\n\n // Creates a file, directory, or symlink at the specified path, recursively creating parent directories if they don't already exist.\n //\n // - Parameters:\n // - path: The FilePath representing the path where the file, directory, or symlink should be created.\n // - link: An optional FilePath representing the target path for a symlink. If `nil`, a regular file or directory will be created. Preceding '/' should be omitted\n // - mode: The permissions to set for the created file, directory, or symlink.\n // - buf: An `InputStream` object providing the contents for the created file. Ignored when creating directories or symlinks.\n //\n // - Note:\n // - This function recursively creates parent directories if they don't already exist. The `uid` and `gid` of the created parent directories are set to the values of their parent's `uid` and `gid`.\n // - It is expected that the user sets the permissions explicitly later\n // - This function only supports creating files, directories, and symlinks. Attempting to create other types of file system objects will result in an error.\n // - In case of symlinks, the preceding '/' should be omitted\n //\n // - Example usage:\n // ```swift\n // let formatter = EXT4.Formatter(devicePath: \"ext4.img\")\n // // create a directory\n // try formatter.create(path: FilePath(\"/dir\"),\n // mode: EXT4.Inode.Mode(.S_IFDIR, 0o700))\n //\n // // create a file\n // let inputStream = InputStream(data: \"data\".data(using: .utf8)!)\n // inputStream.open()\n // try formatter.create(path: FilePath(\"/dir/file\"),\n // mode: EXT4.Inode.Mode(.S_IFREG, 0o755), buf: inputStream)\n // inputStream.close()\n //\n // // create a symlink\n // try formatter.create(path: FilePath(\"/symlink\"), link: \"/dir/file\",\n // mode: EXT4.Inode.Mode(.S_IFLNK, 0o700))\n // ```\n public func create(\n path: FilePath,\n link: FilePath? = nil, // to create symbolic links\n mode: UInt16,\n ts: FileTimestamps = FileTimestamps(),\n buf: InputStream? = nil,\n uid: UInt32? = nil,\n gid: UInt32? = nil,\n xattrs: [String: Data]? = nil,\n recursion: Bool = false\n ) throws {\n if let nodePtr = self.tree.lookup(path: path) {\n let node = nodePtr.pointee\n let inodePtr = self.inodes[Int(node.inode) - 1]\n let inode = inodePtr.pointee\n // Allowed replace\n // -----------------------------\n //\n // Original Type File Directory Symlink\n // ----------------------------------------------\n // File | ✔ | ✘ | ✔\n // Directory | ✘ | ✔ | ✔\n // Symlink | ✔ | ✘ | ✔\n if mode.isDir() {\n if !inode.mode.isDir() {\n guard inode.mode.isLink() else {\n throw Error.notDirectory(path)\n }\n }\n // mkdir -p\n if path.base == node.name {\n guard !recursion else {\n return\n }\n // create a new tree node to replace this one\n var inode = inode\n inode.mode = mode\n if let uid {\n inode.uid = uid.lo\n inode.uidHigh = uid.hi\n }\n if let gid {\n inode.gid = gid.lo\n inode.gidHigh = gid.hi\n }\n inodePtr.initialize(to: inode)\n return\n }\n } else if let _ = node.link { // ok to overwrite links\n try self.unlink(path: path)\n } else { // file can only be overwritten by another file\n if inode.mode.isDir() {\n guard mode.isLink() else { // unless it is a link, then it can be replaced by a dir\n throw Error.notFile(path)\n }\n }\n try self.unlink(path: path)\n }\n }\n // create all predecessors recursively\n let parentPath: FilePath = path.dir\n try self.create(path: parentPath, mode: Inode.Mode(.S_IFDIR, 0o755), recursion: true)\n guard let parentTreeNodePtr = self.tree.lookup(path: parentPath) else {\n throw Error.notFound(parentPath)\n }\n let parentTreeNode = parentTreeNodePtr.pointee\n let parentInodePtr = self.inodes[Int(parentTreeNode.inode) - 1]\n var parentInode = parentInodePtr.pointee\n guard parentInode.linksCount < EXT4.MaxLinks else {\n throw Error.maximumLinksExceeded(parentPath)\n }\n\n let childInodePtr = Ptr.allocate(capacity: 1)\n var childInode = Inode()\n var startBlock: UInt32 = 0\n var endBlock: UInt32 = 0\n defer { // update metadata\n childInodePtr.initialize(to: childInode)\n parentInodePtr.initialize(to: parentInode)\n self.inodes.append(childInodePtr)\n let childTreeNodePtr = Ptr.allocate(capacity: 1)\n let childTreeNode = FileTree.FileTreeNode(\n inode: InodeNumber(self.inodes.count),\n name: path.base,\n parent: parentTreeNodePtr,\n children: [],\n blocks: (startBlock, endBlock)\n )\n childTreeNodePtr.initialize(to: childTreeNode)\n parentTreeNode.children.append(childTreeNodePtr)\n parentTreeNodePtr.initialize(to: parentTreeNode)\n }\n childInode.mode = mode\n // uid,gid\n if let uid {\n childInode.uid = UInt16(uid & 0xffff)\n childInode.uidHigh = UInt16((uid >> 16) & 0xffff)\n } else {\n childInode.uid = parentInode.uid\n childInode.uidHigh = parentInode.uidHigh\n }\n if let gid {\n childInode.gid = UInt16(gid & 0xffff)\n childInode.gidHigh = UInt16((gid >> 16) & 0xffff)\n } else {\n childInode.gid = parentInode.gid\n childInode.gidHigh = parentInode.gidHigh\n }\n if let xattrs, !xattrs.isEmpty {\n var state = FileXattrsState(\n inode: UInt32(self.inodes.count), inodeXattrCapacity: EXT4.InodeExtraSize, blockCapacity: blockSize)\n try state.add(ExtendedAttribute(name: \"system.data\", value: []))\n for (s, d) in xattrs {\n let attribute = ExtendedAttribute(name: s, value: [UInt8](d))\n try state.add(attribute)\n }\n if !state.inlineAttributes.isEmpty {\n var buffer: [UInt8] = .init(repeating: 0, count: Int(EXT4.InodeExtraSize))\n try state.writeInlineAttributes(buffer: &buffer)\n childInode.inlineXattrs = (\n buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5], buffer[6], buffer[7],\n buffer[8],\n buffer[9],\n buffer[10], buffer[11], buffer[12], buffer[13], buffer[14], buffer[15], buffer[16], buffer[17],\n buffer[18],\n buffer[19],\n buffer[20], buffer[21], buffer[22], buffer[23], buffer[24], buffer[25], buffer[26], buffer[27],\n buffer[28],\n buffer[29],\n buffer[30], buffer[31], buffer[32], buffer[33], buffer[34], buffer[35], buffer[36], buffer[37],\n buffer[38],\n buffer[39],\n buffer[40], buffer[41], buffer[42], buffer[43], buffer[44], buffer[45], buffer[46], buffer[47],\n buffer[48],\n buffer[49],\n buffer[50], buffer[51], buffer[52], buffer[53], buffer[54], buffer[55], buffer[56], buffer[57],\n buffer[58],\n buffer[59],\n buffer[60], buffer[61], buffer[62], buffer[63], buffer[64], buffer[65], buffer[66], buffer[67],\n buffer[68],\n buffer[69],\n buffer[70], buffer[71], buffer[72], buffer[73], buffer[74], buffer[75], buffer[76], buffer[77],\n buffer[78],\n buffer[79],\n buffer[80], buffer[81], buffer[82], buffer[83], buffer[84], buffer[85], buffer[86], buffer[87],\n buffer[88],\n buffer[89],\n buffer[90], buffer[91], buffer[92], buffer[93], buffer[94], buffer[95]\n )\n childInode.flags |= InodeFlag.inlineData.rawValue\n }\n if !state.blockAttributes.isEmpty {\n var buffer: [UInt8] = .init(repeating: 0, count: Int(blockSize))\n try state.writeBlockAttributes(buffer: &buffer)\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n childInode.xattrBlockLow = self.currentBlock\n try self.handle.write(contentsOf: buffer)\n childInode.blocksLow += 1\n }\n }\n\n childInode.atime = ts.accessLo\n childInode.atimeExtra = ts.accessHi\n // ctime is the last time the inode was changed which is now\n childInode.ctime = ts.nowLo\n childInode.ctimeExtra = ts.nowHi\n childInode.mtime = ts.modificationLo\n childInode.mtimeExtra = ts.modificationHi\n childInode.crtime = ts.creationLo\n childInode.crtimeExtra = ts.creationHi\n childInode.linksCount = 1\n childInode.extraIsize = UInt16(EXT4.ExtraIsize)\n // flags\n childInode.flags = InodeFlag.hugeFile.rawValue\n // size check\n var size: UInt64 = 0\n // align with block boundary\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n // dir\n if childInode.mode.isDir() {\n childInode.linksCount += 1\n parentInode.linksCount += 1\n // to pass e2fsck, the convention is to sort children\n // before committing to disk. Therefore, we are deferring\n // writing dentries until commit() is called\n return\n }\n // symbolic link\n if let link {\n startBlock = self.currentBlock\n let linkPath = link.bytes\n if linkPath.count < 60 {\n size += UInt64(linkPath.count)\n var blockData: [UInt8] = .init(repeating: 0, count: 60)\n for i in 0...allocate(capacity: Int(self.blockSize))\n defer { tempBuf.deallocate() }\n while case let block = buf.read(tempBuf.underlying, maxLength: Int(self.blockSize)), block > 0 {\n size += UInt64(block)\n if size > EXT4.MaxFileSize {\n throw Error.fileTooBig(size)\n }\n let data = UnsafeRawBufferPointer(start: tempBuf.underlying, count: block)\n try withUnsafeLittleEndianBuffer(of: data) { b in\n try self.handle.write(contentsOf: b)\n }\n }\n }\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n endBlock = self.currentBlock\n childInode.sizeLow = size.lo\n childInode.sizeHigh = size.hi\n childInode = try self.writeExtents(childInode, (startBlock, endBlock))\n return\n }\n // FIFO, Socket and other types are not handled\n throw Error.unsupportedFiletype\n }\n\n public func setOwner(path: FilePath, uid: UInt16? = nil, gid: UInt16? = nil, recursive: Bool = false) throws {\n // ensure that target exists\n guard let pathPtr = self.tree.lookup(path: path) else {\n throw Error.notFound(path)\n }\n let pathNode = pathPtr.pointee\n let pathInodePtr = self.inodes[Int(pathNode.inode) - 1]\n var pathInode = pathInodePtr.pointee\n if let uid {\n pathInode.uid = uid\n }\n if let gid {\n pathInode.gid = gid\n }\n pathInodePtr.initialize(to: pathInode)\n if recursive {\n for childPtr in pathNode.children {\n let child = childPtr.pointee\n try self.setOwner(path: path.join(child.name), uid: uid, gid: gid, recursive: recursive)\n }\n }\n }\n\n // Completes the formatting of an ext4 filesystem after writing the necessary structures.\n //\n // This function is responsible for finalizing the formatting process of an ext4 filesystem\n // after the following structures have been written:\n // - Inode table: Contains information about each file and directory in the filesystem.\n // - Block bitmap: Tracks the allocation status of each block in the filesystem.\n // - Inode bitmap: Tracks the allocation status of each inode in the filesystem.\n // - Directory tree: Represents the hierarchical structure of directories and files.\n // - Group descriptors: Stores metadata about each block group in the filesystem.\n // - Superblock: Contains essential information about the filesystem's configuration.\n //\n // The function performs any necessary final steps to ensure the integrity and consistency\n // of the ext4 filesystem before it can be mounted and used.\n public func close() throws {\n var breathWiseChildTree: [(parent: Ptr?, child: Ptr)] = [\n (nil, self.tree.root)\n ]\n while !breathWiseChildTree.isEmpty {\n let (parent, child) = breathWiseChildTree.removeFirst()\n try self.commit(parent, child) // commit directories iteratively\n if child.pointee.link != nil {\n continue\n }\n breathWiseChildTree.append(contentsOf: child.pointee.children.map { (child, $0) })\n }\n let blockGroupSize = optimizeBlockGroupLayout(blocks: self.currentBlock, inodes: UInt32(self.inodes.count))\n let inodeTableOffset = try self.commitInodeTable(\n blockGroups: blockGroupSize.blockGroups,\n inodesPerGroup: blockGroupSize.inodesPerGroup\n )\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n // write bitmaps and group descriptors\n\n let bitmapOffset = self.currentBlock\n let bitmapSize: UInt32 = blockGroupSize.blockGroups * 2 // each group has two bitmaps - for inodes, and for blocks\n let dataSize: UInt32 = bitmapOffset + bitmapSize // last data block\n var diskSize = dataSize\n var minimumDiskSize = (blockGroupSize.blockGroups - 1) * self.blocksPerGroup + 1\n if blockGroupSize.blockGroups == 1 {\n minimumDiskSize = self.blocksPerGroup // at least 1 block group\n }\n if diskSize < minimumDiskSize { // for data + metadata\n diskSize = minimumDiskSize\n }\n if self.size < minimumDiskSize {\n self.size = UInt64(minimumDiskSize) * self.blockSize\n }\n // number of blocks needed for group descriptors\n let groupDescriptorBlockCount: UInt32 = (blockGroupSize.blockGroups - 1) / self.groupsPerDescriptorBlock + 1\n guard groupDescriptorBlockCount <= self.groupDescriptorBlocks else {\n throw Error.insufficientSpaceForGroupDescriptorBlocks\n }\n\n var totalBlocks: UInt32 = 0\n var totalInodes: UInt32 = 0\n let inodeTableSizePerGroup: UInt32 = blockGroupSize.inodesPerGroup * EXT4.InodeSize / self.blockSize\n var groupDescriptors: [GroupDescriptor] = []\n\n let minGroups = (((self.pos / UInt64(self.blockSize)) - 1) / UInt64(self.blocksPerGroup)) + 1\n if self.size < minGroups * blocksPerGroup * blockSize {\n self.size = UInt64(minGroups * blocksPerGroup * blockSize)\n let pos = self.pos\n guard lseek(self.handle.fileDescriptor, off_t(self.size - 1), 0) == self.size - 1 else {\n throw Error.cannotResizeFS(self.size)\n }\n let zero: [UInt8] = [0]\n try self.handle.write(contentsOf: zero)\n try self.handle.seek(toOffset: pos)\n }\n let totalGroups = (((self.size / UInt64(self.blockSize)) - 1) / UInt64(self.blocksPerGroup)) + 1\n\n // If the provided disk size is not aligned to a blockgroup boundary, it needs to\n // be expanded to the next blockgroup boundary.\n // Example:\n // Provided disk size: 2 GB + 100MB: 2148 MB\n // BlockSize: 4096\n // Blockgroup size: 32768 blocks: 128MB\n // Number of blocks: 549888\n // Number of blockgroups = 549888 / 32768 = 16.78125\n // Aligned disk size = 557056 blocks = 17 blockgroups: 2176 MB\n if self.size < totalGroups * blocksPerGroup * blockSize {\n self.size = UInt64(totalGroups * blocksPerGroup * blockSize)\n let pos = self.pos\n guard lseek(self.handle.fileDescriptor, off_t(self.size - 1), 0) == self.size - 1 else {\n throw Error.cannotResizeFS(self.size)\n }\n let zero: [UInt8] = [0]\n try self.handle.write(contentsOf: zero)\n try self.handle.seek(toOffset: pos)\n }\n for group in 0..> (j % 8)) & 1)\n bitmap[Int(j / 8)] &= ~(1 << (j % 8))\n }\n }\n\n // inodes bitmap goes into second bitmap block\n for i in 0.. self.inodes.count {\n continue\n }\n let inode = self.inodes[Int(ino) - 1]\n if ino > 10 && inode.pointee.linksCount == 0 { // deleted files\n continue\n }\n bitmap[Int(self.blockSize) + Int(i / 8)] |= 1 << (i % 8)\n inodes += 1\n if inode.pointee.mode.isDir() {\n dirs += 1\n }\n }\n\n for i in (blockGroupSize.inodesPerGroup / 8)...init(repeating: 0, count: 1024))\n\n let computedInodes = totalGroups * blockGroupSize.inodesPerGroup\n var blocksCount = totalGroups * self.blocksPerGroup\n while blocksCount < totalBlocks {\n blocksCount = UInt64(totalBlocks)\n }\n let totalFreeBlocks: UInt64\n if totalBlocks > blocksCount {\n totalFreeBlocks = 0\n } else {\n totalFreeBlocks = blocksCount - totalBlocks\n }\n var superblock = SuperBlock()\n superblock.inodesCount = computedInodes.lo\n superblock.blocksCountLow = blocksCount.lo\n superblock.blocksCountHigh = blocksCount.hi\n superblock.freeBlocksCountLow = totalFreeBlocks.lo\n superblock.freeBlocksCountHigh = totalFreeBlocks.hi\n let freeInodesCount = computedInodes.lo - totalInodes\n superblock.freeInodesCount = freeInodesCount\n superblock.firstDataBlock = 0\n superblock.logBlockSize = 2\n superblock.logClusterSize = 2\n superblock.blocksPerGroup = self.blocksPerGroup\n superblock.clustersPerGroup = self.blocksPerGroup\n superblock.inodesPerGroup = blockGroupSize.inodesPerGroup\n superblock.magic = EXT4.SuperBlockMagic\n superblock.state = 1 // cleanly unmounted\n superblock.errors = 1 // continue on error\n superblock.creatorOS = 3 // freeBSD\n superblock.revisionLevel = 1 // dynamic inode sizes\n superblock.firstInode = EXT4.FirstInode\n superblock.lpfInode = EXT4.LostAndFoundInode\n superblock.inodeSize = UInt16(EXT4.InodeSize)\n superblock.featureCompat = CompatFeature.sparseSuper2 | CompatFeature.extAttr\n superblock.featureIncompat =\n IncompatFeature.filetype | IncompatFeature.extents | IncompatFeature.flexBg | IncompatFeature.inlineData\n superblock.featureRoCompat =\n RoCompatFeature.largeFile | RoCompatFeature.hugeFile | RoCompatFeature.extraIsize\n superblock.minExtraIsize = EXT4.ExtraIsize\n superblock.wantExtraIsize = EXT4.ExtraIsize\n superblock.logGroupsPerFlex = 31\n superblock.uuid = UUID().uuid\n try withUnsafeLittleEndianBytes(of: superblock) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n try self.handle.write(contentsOf: Array.init(repeating: 0, count: 2048))\n }\n\n // MARK: Private Methods and Properties\n private var handle: FileHandle\n private var inodes: [Ptr]\n private var tree: FileTree\n private var deletedBlocks: [(start: UInt32, end: UInt32)] = []\n\n private var pos: UInt64 {\n guard let offset = try? self.handle.offset() else {\n return 0\n }\n return offset\n }\n\n private var currentBlock: UInt32 {\n self.pos / self.blockSize\n }\n\n private func seek(block: UInt32) throws {\n try self.handle.seek(toOffset: UInt64(block) * blockSize)\n }\n\n private func commitInodeTable(blockGroups: UInt32, inodesPerGroup: UInt32) throws -> UInt64 {\n // inodeTable must go into a new block\n if self.pos % blockSize != 0 {\n try seek(block: currentBlock + 1)\n }\n let inodeTableOffset = UInt64(currentBlock)\n\n let inodeSize = MemoryLayout.size\n // Write InodeTable\n for inode in self.inodes {\n try withUnsafeLittleEndianBytes(of: inode.pointee) { bytes in\n try handle.write(contentsOf: bytes)\n }\n try self.handle.write(\n contentsOf: Array.init(repeating: 0, count: Int(EXT4.InodeSize) - inodeSize))\n }\n let tableSize: UInt64 = UInt64(EXT4.InodeSize) * blockGroups * inodesPerGroup\n let rest = tableSize - uint32(self.inodes.count) * EXT4.InodeSize\n let zeroBlock = Array.init(repeating: 0, count: Int(self.blockSize))\n for _ in 0..<(rest / self.blockSize) {\n try self.handle.write(contentsOf: zeroBlock)\n }\n try self.handle.write(contentsOf: Array.init(repeating: 0, count: Int(rest % self.blockSize)))\n return inodeTableOffset\n }\n\n // optimizes the distribution of blockGroups to obtain the lowest number of blockGroups needed to\n // represent all the inodes and all the blocks in the FS\n private func optimizeBlockGroupLayout(blocks: UInt32, inodes: UInt32) -> (\n blockGroups: UInt32, inodesPerGroup: UInt32\n ) {\n // counts the number of blockGroups given a particular inodesPerGroup size\n let groupCount: (_ blocks: UInt32, _ inodes: UInt32, _ inodesPerGroup: UInt32) -> UInt32 = {\n blocks, inodes, inodesPerGroup in\n let inodeBlocksPerGroup: UInt32 = inodesPerGroup * EXT4.InodeSize / self.blockSize\n let dataBlocksPerGroup: UInt32 = self.blocksPerGroup - inodeBlocksPerGroup - 2 // save room for the bitmaps\n // Increase the block count to ensure there are enough groups for all the inodes.\n let minBlocks: UInt32 = (inodes - 1) / inodesPerGroup * dataBlocksPerGroup + 1\n var updatedBlocks = blocks\n if blocks < minBlocks {\n updatedBlocks = minBlocks\n }\n return (updatedBlocks + dataBlocksPerGroup - 1) / dataBlocksPerGroup\n }\n\n var groups: UInt32 = UInt32.max\n var inodesPerGroup: UInt32 = 0\n let inc = Int(self.blockSize * 512) / Int(EXT4.InodeSize) // inodesPerGroup\n // minimizes the number of blockGroups needed to its lowest value\n for ipg in stride(from: inc, through: Int(self.maxInodesPerGroup), by: inc) {\n let g = groupCount(blocks, inodes, UInt32(ipg))\n if g < groups {\n groups = g\n inodesPerGroup = UInt32(ipg)\n }\n }\n return (groups, inodesPerGroup)\n }\n\n private func commit(_ parentPtr: Ptr?, _ nodePtr: Ptr) throws {\n let node = nodePtr.pointee\n let inodePtr = self.inodes[Int(node.inode) - 1]\n var inode = inodePtr.pointee\n guard inode.linksCount > 0 else {\n return\n }\n if node.link != nil {\n return\n }\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n if inode.mode.isDir() {\n let startBlock = self.currentBlock\n var left: Int = Int(self.blockSize)\n try writeDirEntry(name: \".\", inode: node.inode, left: &left)\n if let parent = parentPtr {\n try writeDirEntry(name: \"..\", inode: parent.pointee.inode, left: &left)\n } else {\n try writeDirEntry(name: \"..\", inode: node.inode, left: &left)\n }\n var sortedChildren = Array(node.children)\n sortedChildren.sort { left, right in\n left.pointee.inode < right.pointee.inode\n }\n for childPtr in sortedChildren {\n let child = childPtr.pointee\n try writeDirEntry(name: child.name, inode: child.inode, left: &left, link: child.link)\n }\n try finishDirEntryBlock(&left)\n let endBlock = self.currentBlock\n let size: UInt64 = UInt64(endBlock - startBlock) * self.blockSize\n inode.sizeLow = size.lo\n inode.sizeHigh = size.hi\n inodePtr.initialize(to: inode)\n node.blocks = (startBlock, endBlock)\n nodePtr.initialize(to: node)\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n inode = try self.writeExtents(inode, (startBlock, endBlock))\n inodePtr.initialize(to: inode)\n }\n }\n\n private func fillExtents(\n node: inout ExtentLeafNode, numExtents: UInt32, numBlocks: UInt32, start: UInt32, offset: UInt32\n ) {\n for i in 0.. EXT4.MaxBlocksPerExtent {\n length = EXT4.MaxBlocksPerExtent\n }\n let extentStart: UInt32 = start + extentBlock\n let extent = ExtentLeaf(\n block: extentBlock,\n length: UInt16(length),\n startHigh: 0,\n startLow: extentStart\n )\n node.leaves.append(extent)\n }\n }\n\n private func writeExtents(_ inode: Inode, _ blocks: (start: UInt32, end: UInt32)) throws -> Inode {\n var inode = inode\n // rest of code assumes that extents MUST go into a new block\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n let dataBlocks = blocks.end - blocks.start\n let numExtents = (dataBlocks + EXT4.MaxBlocksPerExtent - 1) / EXT4.MaxBlocksPerExtent\n var usedBlocks = dataBlocks\n let extentNodeSize = 12\n let extentsPerBlock = self.blockSize / extentNodeSize - 1\n var blockData: [UInt8] = .init(repeating: 0, count: 60)\n var blockIndex: Int = 0\n switch numExtents {\n case 0:\n return inode // noop\n case 1..<5:\n let extentHeader = ExtentHeader(\n magic: EXT4.ExtentHeaderMagic,\n entries: UInt16(numExtents),\n max: 4,\n depth: 0,\n generation: 0)\n\n var node = ExtentLeafNode(header: extentHeader, leaves: [])\n fillExtents(node: &node, numExtents: numExtents, numBlocks: dataBlocks, start: blocks.start, offset: 0)\n withUnsafeLittleEndianBytes(of: node.header) { bytes in\n for b in bytes {\n blockData[blockIndex] = b\n blockIndex = blockIndex + 1\n }\n }\n for leaf in node.leaves {\n withUnsafeLittleEndianBytes(of: leaf) { bytes in\n for b in bytes {\n blockData[blockIndex] = b\n blockIndex = blockIndex + 1\n }\n }\n }\n case 5..<4 * UInt32(extentsPerBlock) + 1:\n let extentBlocks = numExtents / extentsPerBlock + 1\n usedBlocks += extentBlocks\n let extentHeader = ExtentHeader(\n magic: EXT4.ExtentHeaderMagic,\n entries: UInt16(extentBlocks),\n max: 4,\n depth: 1,\n generation: 0\n )\n var root = ExtentIndexNode(header: extentHeader, indices: [])\n for i in 0.. extentsPerBlock {\n extentsInBlock = extentsPerBlock\n }\n let leafHeader = ExtentHeader(\n magic: EXT4.ExtentHeaderMagic,\n entries: UInt16(extentsInBlock),\n max: UInt16(extentsPerBlock),\n depth: 0,\n generation: 0\n )\n var leafNode = ExtentLeafNode(header: leafHeader, leaves: [])\n let offset = i * extentsPerBlock * EXT4.MaxBlocksPerExtent\n fillExtents(\n node: &leafNode, numExtents: extentsInBlock, numBlocks: dataBlocks,\n start: blocks.start + offset,\n offset: offset)\n try withUnsafeLittleEndianBytes(of: leafNode.header) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n for leaf in leafNode.leaves {\n try withUnsafeLittleEndianBytes(of: leaf) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n }\n let extentTail = ExtentTail(checksum: leafNode.leaves.last!.block)\n try withUnsafeLittleEndianBytes(of: extentTail) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n root.indices.append(extentIdx)\n }\n withUnsafeLittleEndianBytes(of: root.header) { bytes in\n for b in bytes {\n blockData[blockIndex] = b\n blockIndex = blockIndex + 1\n }\n }\n for leaf in root.indices {\n withUnsafeLittleEndianBytes(of: leaf) { bytes in\n for b in bytes {\n blockData[blockIndex] = b\n blockIndex = blockIndex + 1\n }\n }\n }\n default:\n throw Error.fileTooBig(UInt64(dataBlocks) * self.blockSize)\n }\n inode.block = (\n blockData[0], blockData[1], blockData[2], blockData[3], blockData[4], blockData[5], blockData[6],\n blockData[7],\n blockData[8], blockData[9],\n blockData[10], blockData[11], blockData[12], blockData[13], blockData[14], blockData[15], blockData[16],\n blockData[17], blockData[18], blockData[19],\n blockData[20], blockData[21], blockData[22], blockData[23], blockData[24], blockData[25], blockData[26],\n blockData[27], blockData[28], blockData[29],\n blockData[30], blockData[31], blockData[32], blockData[33], blockData[34], blockData[35], blockData[36],\n blockData[37], blockData[38], blockData[39],\n blockData[40], blockData[41], blockData[42], blockData[43], blockData[44], blockData[45], blockData[46],\n blockData[47], blockData[48], blockData[49],\n blockData[50], blockData[51], blockData[52], blockData[53], blockData[54], blockData[55], blockData[56],\n blockData[57], blockData[58], blockData[59]\n )\n // ensure that inode's block count includes extent blocks\n inode.blocksLow += usedBlocks\n inode.flags = InodeFlag.extents | inode.flags\n return inode\n }\n // writes a single directory entry\n private func writeDirEntry(name: String, inode: InodeNumber, left: inout Int, link: InodeNumber? = nil) throws {\n guard self.inodes[Int(inode) - 1].pointee.linksCount > 0 else {\n return\n }\n guard let nameData = name.data(using: .utf8) else {\n throw Error.invalidName(name)\n }\n let directoryEntrySize = MemoryLayout.size\n let rlb = directoryEntrySize + nameData.count\n let rl = (rlb + 3) & ~3\n if left < rl + 12 {\n try self.finishDirEntryBlock(&left)\n }\n var mode = self.inodes[Int(inode) - 1].pointee.mode\n var inodeNum = inode\n if let link {\n mode = self.inodes[Int(link) - 1].pointee.mode | 0o777\n inodeNum = link\n }\n let entry = DirectoryEntry(\n inode: inodeNum,\n recordLength: UInt16(rl),\n nameLength: UInt8(nameData.count),\n fileType: mode.fileType()\n )\n try withUnsafeLittleEndianBytes(of: entry) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n\n try nameData.withUnsafeBytes { buffer in\n try withUnsafeLittleEndianBuffer(of: buffer) { b in\n try self.handle.write(contentsOf: b)\n }\n }\n try self.handle.write(contentsOf: [UInt8](repeating: 0, count: rl - rlb))\n left = left - rl\n }\n\n private func finishDirEntryBlock(_ left: inout Int) throws {\n defer { left = Int(self.blockSize) }\n if left <= 0 {\n return\n }\n let entry = DirectoryEntry(\n inode: InodeNumber(0),\n recordLength: UInt16(left),\n nameLength: 0,\n fileType: 0\n )\n try withUnsafeLittleEndianBytes(of: entry) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n left = left - MemoryLayout.size\n if left < 4 {\n throw Error.noSpaceForTrailingDEntry\n }\n try self.handle.write(contentsOf: [UInt8](repeating: 0, count: Int(left)))\n }\n\n public enum Error: Swift.Error, CustomStringConvertible, Sendable, Equatable {\n case notDirectory(_ path: FilePath)\n case notFile(_ path: FilePath)\n case notFound(_ path: FilePath)\n case alreadyExists(_ path: FilePath)\n case unsupportedFiletype\n case maximumLinksExceeded(_ path: FilePath)\n case fileTooBig(_ size: UInt64)\n case invalidLink(_ path: FilePath)\n case invalidName(_ name: String)\n case noSpaceForTrailingDEntry\n case insufficientSpaceForGroupDescriptorBlocks\n case cannotCreateHardlinksToDirTarget(_ path: FilePath)\n case cannotTruncateFile(_ path: FilePath)\n case cannotCreateSparseFile(_ path: FilePath)\n case cannotResizeFS(_ size: UInt64)\n public var description: String {\n switch self {\n case .notDirectory(let path):\n return \"\\(path) is not a directory\"\n case .notFile(let path):\n return \"\\(path) is not a file\"\n case .notFound(let path):\n return \"\\(path) not found\"\n case .alreadyExists(let path):\n return \"\\(path) already exists\"\n case .unsupportedFiletype:\n return \"file type not supported\"\n case .maximumLinksExceeded(let path):\n return \"maximum links exceeded for path: \\(path)\"\n case .fileTooBig(let size):\n return \"\\(size) exceeds max file size (128 GiB)\"\n case .invalidLink(let path):\n return \"'\\(path)' is an invalid link\"\n case .invalidName(let name):\n return \"'\\(name)' is an invalid name\"\n case .noSpaceForTrailingDEntry:\n return \"not enough space for trailing dentry\"\n case .insufficientSpaceForGroupDescriptorBlocks:\n return \"not enough space for group descriptor blocks\"\n case .cannotCreateHardlinksToDirTarget(let path):\n return \"cannot create hard links to directory target: \\(path)\"\n case .cannotTruncateFile(let path):\n return \"cannot truncate file: \\(path)\"\n case .cannotCreateSparseFile(let path):\n return \"cannot create sparse file at \\(path)\"\n case .cannotResizeFS(let size):\n return \"cannot resize fs to \\(size) bytes\"\n }\n }\n }\n\n deinit {\n for inode in inodes {\n inode.deinitialize(count: 1)\n inode.deallocate()\n }\n self.inodes.removeAll()\n }\n }\n}\n\nextension Date {\n func fs() -> UInt64 {\n if self == Date.distantPast {\n return 0\n }\n\n let s = self.timeIntervalSince1970\n\n if s < -0x8000_0000 {\n return 0x8000_0000\n }\n\n if s > 0x3_7fff_ffff {\n return 0x3_7fff_ffff\n }\n\n let seconds = UInt64(s)\n let nanoseconds = UInt64(self.timeIntervalSince1970.truncatingRemainder(dividingBy: 1) * 1_000_000_000)\n\n return seconds | (nanoseconds << 34)\n }\n}\n"], ["/containerization/Sources/Containerization/TimeSyncer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Logging\n\nactor TimeSyncer: Sendable {\n private var task: Task?\n private var context: Vminitd?\n private let logger: Logger?\n\n init(logger: Logger?) {\n self.logger = logger\n }\n\n func start(context: Vminitd, interval: Duration = .seconds(30)) {\n precondition(task == nil, \"time syncer is already running\")\n self.context = context\n self.task = Task {\n while true {\n do {\n do {\n try await Task.sleep(for: interval)\n } catch {\n return\n }\n\n var timeval = timeval()\n guard gettimeofday(&timeval, nil) == 0 else {\n throw POSIXError.fromErrno()\n }\n\n try await context.setTime(\n sec: Int64(timeval.tv_sec),\n usec: Int32(timeval.tv_usec)\n )\n } catch {\n self.logger?.error(\"failed to sync time with guest agent: \\(error)\")\n }\n }\n }\n }\n\n func close() async throws {\n guard let task else {\n preconditionFailure(\"time syncer was already closed\")\n }\n\n task.cancel()\n try await self.context?.close()\n self.task = nil\n self.context = nil\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/RegistryClient+Fetch.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport ContainerizationError\nimport ContainerizationExtras\nimport Crypto\nimport Foundation\nimport NIOFoundationCompat\n\n#if os(macOS)\nimport NIOFileSystem\n#endif\n\nextension RegistryClient {\n /// Resolve sends a HEAD request to the registry to find root manifest descriptor.\n /// This descriptor serves as an entry point to retrieve resources from the registry.\n public func resolve(name: String, tag: String) async throws -> Descriptor {\n var components = base\n\n // Make HEAD request to retrieve the digest header\n components.path = \"/v2/\\(name)/manifests/\\(tag)\"\n\n // The client should include an Accept header indicating which manifest content types it supports.\n let mediaTypes = [\n MediaTypes.dockerManifest,\n MediaTypes.dockerManifestList,\n MediaTypes.imageManifest,\n MediaTypes.index,\n \"*/*\",\n ]\n\n let headers = [\n (\"Accept\", mediaTypes.joined(separator: \", \"))\n ]\n\n return try await request(components: components, method: .HEAD, headers: headers) { response in\n guard response.status == .ok else {\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n\n guard let digest = response.headers.first(name: \"Docker-Content-Digest\") else {\n throw ContainerizationError(.invalidArgument, message: \"Missing required header Docker-Content-Digest\")\n }\n\n guard let type = response.headers.first(name: \"Content-Type\") else {\n throw ContainerizationError(.invalidArgument, message: \"Missing required header Content-Type\")\n }\n\n guard let sizeStr = response.headers.first(name: \"Content-Length\") else {\n throw ContainerizationError(.invalidArgument, message: \"Missing required header Content-Length\")\n }\n\n guard let size = Int64(sizeStr) else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot convert \\(sizeStr) to Int64\")\n }\n\n return Descriptor(mediaType: type, digest: digest, size: size)\n }\n }\n\n /// Fetch resource (either manifest or blob) to memory with JSON decoding.\n public func fetch(name: String, descriptor: Descriptor) async throws -> T {\n var components = base\n\n let manifestTypes = [\n MediaTypes.dockerManifest,\n MediaTypes.dockerManifestList,\n MediaTypes.imageManifest,\n MediaTypes.index,\n ]\n\n let isManifest = manifestTypes.contains(where: { $0 == descriptor.mediaType })\n let resource = isManifest ? \"manifests\" : \"blobs\"\n\n components.path = \"/v2/\\(name)/\\(resource)/\\(descriptor.digest)\"\n\n let mediaType = descriptor.mediaType\n if mediaType.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Missing media type for descriptor \\(descriptor.digest)\")\n }\n\n let headers = [\n (\"Accept\", mediaType)\n ]\n\n return try await requestJSON(components: components, headers: headers)\n }\n\n /// Fetch resource (either manifest or blob) to memory as raw `Data`.\n public func fetchData(name: String, descriptor: Descriptor) async throws -> Data {\n var components = base\n\n let manifestTypes = [\n MediaTypes.dockerManifest,\n MediaTypes.dockerManifestList,\n MediaTypes.imageManifest,\n MediaTypes.index,\n ]\n\n let isManifest = manifestTypes.contains(where: { $0 == descriptor.mediaType })\n let resource = isManifest ? \"manifests\" : \"blobs\"\n\n components.path = \"/v2/\\(name)/\\(resource)/\\(descriptor.digest)\"\n\n let mediaType = descriptor.mediaType\n if mediaType.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Missing media type for descriptor \\(descriptor.digest)\")\n }\n\n let headers = [\n (\"Accept\", mediaType)\n ]\n\n return try await requestData(components: components, headers: headers)\n }\n\n /// Fetch a blob from remote registry.\n /// This method is suitable for streaming data.\n public func fetchBlob(\n name: String,\n descriptor: Descriptor,\n closure: (Int64, HTTPClientResponse.Body) async throws -> Void\n ) async throws {\n var components = base\n components.path = \"/v2/\\(name)/blobs/\\(descriptor.digest)\"\n\n let mediaType = descriptor.mediaType\n if mediaType.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Missing media type for descriptor \\(descriptor.digest)\")\n }\n\n let headers = [\n (\"Accept\", mediaType)\n ]\n\n try await request(components: components, headers: headers) { response in\n guard response.status == .ok else {\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n\n // How many bytes to expect\n guard let expectedBytes = response.headers.first(name: \"Content-Length\").flatMap(Int64.init) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing required header Content-Length\")\n }\n\n try await closure(expectedBytes, response.body)\n }\n }\n\n #if os(macOS)\n /// Fetch a blob from remote registry and write the contents into a file in the provided directory.\n public func fetchBlob(name: String, descriptor: Descriptor, into file: URL, progress: ProgressHandler?) async throws -> (Int64, SHA256Digest) {\n var hasher = SHA256()\n var received: Int64 = 0\n let fs = NIOFileSystem.FileSystem.shared\n let handle = try await fs.openFile(forWritingAt: FilePath(file.absolutePath()), options: .newFile(replaceExisting: true))\n var writer = handle.bufferedWriter()\n do {\n try await self.fetchBlob(name: name, descriptor: descriptor) { (size, body) in\n var itr = body.makeAsyncIterator()\n while let buf = try await itr.next() {\n let readBytes = Int64(buf.readableBytes)\n received += readBytes\n let written = try await writer.write(contentsOf: buf)\n await progress?([\n ProgressEvent(event: \"add-size\", value: written)\n ])\n guard written == readBytes else {\n throw ContainerizationError(\n .internalError,\n message: \"Could not write \\(readBytes) bytes to file \\(file)\"\n )\n }\n hasher.update(data: buf.readableBytesView)\n }\n }\n try await writer.flush()\n try await handle.close()\n } catch {\n try? await handle.close()\n throw error\n }\n let computedDigest = hasher.finalize()\n return (received, computedDigest)\n }\n #else\n /// Fetch a blob from remote registry and write the contents into a file in the provided directory.\n public func fetchBlob(name: String, descriptor: Descriptor, into file: URL, progress: ProgressHandler?) async throws -> (Int64, SHA256Digest) {\n var hasher = SHA256()\n var received: Int64 = 0\n guard FileManager.default.createFile(atPath: file.path, contents: nil) else {\n throw ContainerizationError(.internalError, message: \"Cannot create file at path \\(file.path)\")\n }\n try await self.fetchBlob(name: name, descriptor: descriptor) { (size, body) in\n let fd = try FileHandle(forWritingTo: file)\n defer {\n try? fd.close()\n }\n var itr = body.makeAsyncIterator()\n while let buf = try await itr.next() {\n let readBytes = Int64(buf.readableBytes)\n received += readBytes\n await progress?([\n ProgressEvent(event: \"add-size\", value: readBytes)\n ])\n try fd.write(contentsOf: buf.readableBytesView)\n hasher.update(data: buf.readableBytesView)\n }\n }\n let computedDigest = hasher.finalize()\n return (received, computedDigest)\n }\n #endif\n}\n"], ["/containerization/Sources/Containerization/Image/ImageStore/ImageStore.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\n/// An ImageStore handles the mappings between an image's\n/// reference and the underlying descriptor inside of a content store.\npublic actor ImageStore: Sendable {\n /// The ImageStore path it was created with.\n public nonisolated let path: URL\n\n private let referenceManager: ReferenceManager\n internal let contentStore: ContentStore\n internal let lock: AsyncLock = AsyncLock()\n\n public init(path: URL, contentStore: ContentStore? = nil) throws {\n try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true)\n\n if let contentStore {\n self.contentStore = contentStore\n } else {\n self.contentStore = try LocalContentStore(path: path.appendingPathComponent(\"content\"))\n }\n\n self.path = path\n self.referenceManager = try ReferenceManager(path: path)\n }\n\n /// Return the default image store for the current user.\n public static let `default`: ImageStore = {\n do {\n let root = try defaultRoot()\n return try ImageStore(path: root)\n } catch {\n fatalError(\"unable to initialize default ImageStore \\(error)\")\n }\n }()\n\n private static func defaultRoot() throws -> URL {\n let root = FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first\n guard let root else {\n throw ContainerizationError(.notFound, message: \"unable to get Application Support directory for current user\")\n }\n return root.appendingPathComponent(\"com.apple.containerization\")\n\n }\n}\n\nextension ImageStore {\n /// Get an image from the `ImageStore`.\n ///\n /// - Parameters:\n /// - reference: Name of the image.\n /// - pull: Pull the image if it is not found.\n ///\n /// - Returns: A `Containerization.Image` object whose `reference` matches the given string.\n /// This method throws a `ContainerizationError(code: .notFound)` if the provided reference does not exist in the `ImageStore`.\n public func get(reference: String, pull: Bool = false) async throws -> Image {\n do {\n let desc = try await self.referenceManager.get(reference: reference)\n return Image(description: desc, contentStore: self.contentStore)\n } catch let error as ContainerizationError {\n if error.code == .notFound && pull {\n return try await self.pull(reference: reference)\n }\n throw error\n }\n }\n\n /// Get a list of all images in the `ImageStore`.\n ///\n /// - Returns: A `[Containerization.Image]` for all the images in the `ImageStore`.\n public func list() async throws -> [Image] {\n try await self.referenceManager.list().map { desc in\n Image(description: desc, contentStore: self.contentStore)\n }\n }\n\n /// Create a new image in the `ImageStore`.\n ///\n /// - Parameters:\n /// - description: The underlying `Image.Description` that contains information about the reference and index descriptor for the image to be created.\n ///\n /// - Note: It is assumed that the underlying manifests and blob layers for the image already exists in the `ContentStore` that the `ImageStore` was initialized with. This method is invoked when the `pull(...)` , `load(...)` and `tag(...)` methods are used.\n /// - Returns: A `Containerization.Image`\n @discardableResult\n internal func create(description: Image.Description) async throws -> Image {\n try await self.lock.withLock { ctx in\n try await self._create(description: description, lock: ctx)\n }\n }\n\n @discardableResult\n internal func _create(description: Image.Description, lock: AsyncLock.Context) async throws -> Image {\n try await self.referenceManager.create(description: description)\n return Image(description: description, contentStore: self.contentStore)\n }\n\n /// Delete an image from the `ImageStore`.\n ///\n /// - Parameters:\n /// - reference: Name of the image that is to be deleted.\n /// - performCleanup: Perform a garbage collection on the `ContentStore`, removing all unreferenced image layers and manifests,\n public func delete(reference: String, performCleanup: Bool = false) async throws {\n try await self.lock.withLock { lockCtx in\n try await self.referenceManager.delete(reference: reference)\n if performCleanup {\n try await self._prune(lockCtx)\n }\n }\n }\n\n /// Perform a garbage collection in the underlying `ContentStore` that is managed by the `ImageStore`.\n ///\n /// - Returns: Returns a tuple of `(deleted, freed)`.\n /// `deleted` : A list of the names of the content items that were deleted from the `ContentStore`,\n /// `freed` : The total size of the items that were deleted.\n @discardableResult\n public func prune() async throws -> (deleted: [String], freed: UInt64) {\n try await self.lock.withLock { lockCtx in\n try await self._prune(lockCtx)\n }\n }\n\n @discardableResult\n private func _prune(_ lock: AsyncLock.Context) async throws -> ([String], UInt64) {\n let images = try await self.list()\n var referenced: [String] = []\n for image in images {\n try await referenced.append(contentsOf: image.referencedDigests().uniqued())\n }\n let (deleted, size) = try await self.contentStore.delete(keeping: referenced)\n return (deleted, size)\n\n }\n\n /// Tag an existing image such that it can be referenced by another name.\n ///\n /// - Parameters:\n /// - existing: The reference to an image that already exists in the `ImageStore`.\n /// - new: The new reference by which the image should also be referenced as.\n /// - Note: The new image created in the `ImageStore` will have the same `Image.Description`\n /// as that of the image with reference `existing.`\n /// - Returns: A `Containerization.Image` object to the newly created image.\n public func tag(existing: String, new: String) async throws -> Image {\n let old = try await self.get(reference: existing)\n let descriptor = old.descriptor\n do {\n _ = try Reference.parse(new)\n } catch {\n throw ContainerizationError(.invalidArgument, message: \"Invalid reference \\(new). Error: \\(error)\")\n }\n let newDescription = Image.Description(reference: new, descriptor: descriptor)\n return try await self.create(description: newDescription)\n }\n}\n\nextension ImageStore {\n /// Pull an image and its associated manifest and blob layers from a remote registry.\n ///\n /// - Parameters:\n /// - reference: A string that references an image in a remote registry of the form `[:]/repository:`\n /// For example: \"docker.io/library/alpine:latest\".\n /// - platform: An optional parameter to indicate the platform to be pulled for the image.\n /// Defaults to `nil` signifying that layers for all supported platforms by the image will be pulled.\n /// - insecure: A boolean indicating if the connection to the remote registry should be made via plain-text http or not.\n /// Defaults to false, meaning the connection to the registry will be over https.\n /// - auth: An object that implements the `Authentication` protocol,\n /// used to add any credentials to the HTTP requests that are made to the registry.\n /// Defaults to `nil` meaning no additional credentials are added to any HTTP requests made to the registry.\n /// - progress: An optional handler over which progress update events about the pull operation can be received.\n ///\n /// - Returns: A `Containerization.Image` object to the newly pulled image.\n public func pull(\n reference: String, platform: Platform? = nil, insecure: Bool = false,\n auth: Authentication? = nil, progress: ProgressHandler? = nil\n ) async throws -> Image {\n\n let matcher = createPlatformMatcher(for: platform)\n let client = try RegistryClient(reference: reference, insecure: insecure, auth: auth)\n\n let ref = try Reference.parse(reference)\n let name = ref.path\n guard let tag = ref.tag ?? ref.digest else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid tag/digest for image reference \\(reference)\")\n }\n\n let rootDescriptor = try await client.resolve(name: name, tag: tag)\n let (id, tempDir) = try await self.contentStore.newIngestSession()\n let operation = ImportOperation(name: name, contentStore: self.contentStore, client: client, ingestDir: tempDir, progress: progress)\n do {\n let index = try await operation.import(root: rootDescriptor, matcher: matcher)\n return try await self.lock.withLock { lock in\n try await self.contentStore.completeIngestSession(id)\n let description = Image.Description(reference: reference, descriptor: index)\n let image = try await self._create(description: description, lock: lock)\n return image\n }\n } catch {\n try? await self.contentStore.cancelIngestSession(id)\n throw error\n }\n }\n\n /// Push an image and its associated manifest and blob layers to a remote registry.\n ///\n /// - Parameters:\n /// - reference: A string that references an image in the `ImageStore`. It must be of the form `[:]/repository:`\n /// For example: \"ghcr.io/foo-bar-baz/image:v1\".\n /// - platform: An optional parameter to indicate the platform to be pushed for the image.\n /// Defaults to `nil` signifying that layers for all supported platforms by the image will be pushed to the remote registry.\n /// - insecure: A boolean indicating if the connection to the remote registry should be made via plain-text http or not.\n /// Defaults to false, meaning the connection to the registry will be over https.\n /// - auth: An object that implements the `Authentication` protocol,\n /// used to add any credentials to the HTTP requests that are made to the registry.\n /// Defaults to `nil` meaning no additional credentials are added to any HTTP requests made to the registry.\n /// - progress: An optional handler over which progress update events about the push operation can be received.\n ///\n public func push(reference: String, platform: Platform? = nil, insecure: Bool = false, auth: Authentication? = nil, progress: ProgressHandler? = nil) async throws {\n let matcher = createPlatformMatcher(for: platform)\n let img = try await self.get(reference: reference)\n let allowedMediaTypes = [MediaTypes.dockerManifestList, MediaTypes.index]\n guard allowedMediaTypes.contains(img.mediaType) else {\n throw ContainerizationError(.internalError, message: \"Cannot push image \\(reference) with Index media type \\(img.mediaType)\")\n }\n let ref = try Reference.parse(reference)\n let name = ref.path\n guard let tag = ref.tag ?? ref.digest else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid tag/digest for image reference \\(reference)\")\n }\n let client = try RegistryClient(reference: reference, insecure: insecure, auth: auth)\n let operation = ExportOperation(name: name, tag: tag, contentStore: self.contentStore, client: client, progress: progress)\n try await operation.export(index: img.descriptor, platforms: matcher)\n }\n}\n\nextension ImageStore {\n /// Get the image for the init block from the image store.\n /// If the image does not exist locally, pull the image.\n public func getInitImage(reference: String, auth: Authentication? = nil, progress: ProgressHandler? = nil) async throws -> InitImage {\n do {\n let image = try await self.get(reference: reference)\n return InitImage(image: image)\n } catch let error as ContainerizationError {\n if error.code == .notFound {\n let image = try await self.pull(reference: reference, auth: auth, progress: progress)\n return InitImage(image: image)\n }\n throw error\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/LocalContentStore.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// swiftlint:disable unused_optional_binding\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport Crypto\nimport Foundation\n\n/// A `ContentStore` implementation that stores content on the local filesystem.\npublic actor LocalContentStore: ContentStore {\n private static let encoder = JSONEncoder()\n\n private let _basePath: URL\n private let _ingestPath: URL\n private let _blobPath: URL\n private let _lock: AsyncLock\n\n private var activeIngestSessions: AsyncSet = AsyncSet([])\n\n /// Create a new `LocalContentStore`.\n ///\n /// - Parameters:\n /// - path: The path where content should be written under.\n public init(path: URL) throws {\n let ingestPath = path.appendingPathComponent(\"ingest\")\n let blobPath = path.appendingPathComponent(\"blobs/sha256\")\n\n let fileManager = FileManager.default\n try fileManager.createDirectory(at: ingestPath, withIntermediateDirectories: true)\n try fileManager.createDirectory(at: blobPath, withIntermediateDirectories: true)\n\n self._basePath = path\n self._ingestPath = ingestPath\n self._blobPath = blobPath\n self._lock = AsyncLock()\n Self.encoder.outputFormatting = .sortedKeys\n }\n\n /// Get a piece of content from the store. Returns nil if not\n /// found.\n ///\n /// - Parameters:\n /// - digest: The string digest of the content.\n public func get(digest: String) throws -> Content? {\n let d = digest.trimmingDigestPrefix\n let path = self._blobPath.appendingPathComponent(d)\n do {\n return try LocalContent(path: path)\n } catch let err as ContainerizationError {\n switch err.code {\n case .notFound:\n return nil\n default:\n throw err\n }\n }\n }\n\n /// Get a piece of content from the store and return the decoded version of\n /// it.\n ///\n /// - Parameters:\n /// - digest: The string digest of the content.\n public func get(digest: String) throws -> T? {\n guard let content: Content = try self.get(digest: digest) else {\n return nil\n }\n return try content.decode()\n }\n\n /// Delete all content besides a set provided.\n ///\n /// - Parameters:\n /// - keeping: The set of string digests to keep.\n public func delete(keeping: [String]) async throws -> ([String], UInt64) {\n let fileManager = FileManager.default\n let all = try fileManager.contentsOfDirectory(at: self._blobPath, includingPropertiesForKeys: nil)\n let allDigests = Set(all.map { $0.lastPathComponent })\n let toDelete = allDigests.subtracting(keeping)\n return try await self.delete(digests: Array(toDelete))\n }\n\n /// Delete a specific set of content.\n ///\n /// - Parameters:\n /// - digests: Array of strings denoting the digests of the content to delete.\n @discardableResult\n public func delete(digests: [String]) async throws -> ([String], UInt64) {\n let store = AsyncStore<([String], UInt64)>()\n try await self._lock.withLock { context in\n let fileManager = FileManager.default\n var deleted: [String] = []\n var deletedBytes: UInt64 = 0\n for toDelete in digests {\n let p = self._blobPath.appendingPathComponent(toDelete)\n guard let content = try? LocalContent(path: p) else {\n continue\n }\n deletedBytes += try content.size()\n try fileManager.removeItem(at: p)\n deleted.append(toDelete)\n }\n await store.set((deleted, deletedBytes))\n }\n return await store.get() ?? ([], 0)\n }\n\n /// Creates a transactional write to the content store.\n ///\n /// - Parameters:\n /// - body: Closure that is given a temporary `URL` of the base directory which all contents should be written to.\n /// This is a transaction write where any failed operation in the closure (caught exception) will result in all contents written\n /// in the closure to be deleted. If the closure succeeds, then all the content that have been written to the temporary `URL`\n /// will be moved into the actual blobs path of the content store.\n @discardableResult\n public func ingest(_ body: @Sendable @escaping (URL) async throws -> Void) async throws -> [String] {\n let (id, tempPath) = try await self.newIngestSession()\n try await body(tempPath)\n return try await self.completeIngestSession(id)\n }\n\n /// Creates a new ingest session and returns the session ID and temporary ingest directory corresponding to the session.\n /// The contents from the ingest directory are processed and moved into the content store once the session is marked complete.\n /// This can be done by invoking the `completeIngestSession` method with the returned session ID.\n public func newIngestSession() async throws -> (id: String, ingestDir: URL) {\n let id = UUID().uuidString\n let temporaryPath = self._ingestPath.appendingPathComponent(id)\n let fileManager = FileManager.default\n try fileManager.createDirectory(atPath: temporaryPath.path, withIntermediateDirectories: true)\n await self.activeIngestSessions.insert(id)\n return (id, temporaryPath)\n }\n\n /// Completes a previously started ingest session corresponding to `id`. The contents from the ingest\n /// directory from the session are moved into the content store atomically. Any failure encountered will\n /// result in a transaction failure causing none of the contents to be ingested into the store.\n /// - Parameters:\n /// - id: id of the ingest session to complete.\n @discardableResult\n public func completeIngestSession(_ id: String) async throws -> [String] {\n guard await activeIngestSessions.contains(id) else {\n throw ContainerizationError(.internalError, message: \"Invalid session id \\(id)\")\n }\n await activeIngestSessions.remove(id)\n let temporaryPath = self._ingestPath.appendingPathComponent(id)\n let fileManager = FileManager.default\n defer {\n try? fileManager.removeItem(at: temporaryPath)\n }\n let tempDigests: [URL] = try fileManager.contentsOfDirectory(at: temporaryPath, includingPropertiesForKeys: nil)\n return try await self._lock.withLock { context in\n var moved: [String] = []\n let fileManager = FileManager.default\n do {\n try tempDigests.forEach {\n let digest = $0.lastPathComponent\n let target = self._blobPath.appendingPathComponent(digest)\n // only ingest if not exists\n if !fileManager.fileExists(atPath: target.path) {\n try fileManager.moveItem(at: $0, to: target)\n moved.append(digest)\n }\n }\n } catch {\n moved.forEach {\n try? fileManager.removeItem(at: self._blobPath.appendingPathComponent($0))\n }\n throw error\n }\n return tempDigests.map { $0.lastPathComponent }\n }\n }\n\n /// Cancels a previously started ingest session corresponding to `id`.\n /// The contents from the ingest directory corresponding to the session are removed.\n /// - Parameters:\n /// - id: id of the ingest session to complete.\n public func cancelIngestSession(_ id: String) async throws {\n guard let _ = await self.activeIngestSessions.remove(id) else {\n return\n }\n let temporaryPath = self._ingestPath.appendingPathComponent(id)\n let fileManager = FileManager.default\n try? fileManager.removeItem(at: temporaryPath)\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/Server.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\nimport GRPC\nimport Logging\nimport Musl\nimport NIOCore\nimport NIOPosix\n\nfinal class Initd: Sendable {\n let log: Logger\n let state: State\n let group: MultiThreadedEventLoopGroup\n\n actor State {\n var containers: [String: ManagedContainer] = [:]\n var proxies: [String: VsockProxy] = [:]\n\n func get(container id: String) throws -> ManagedContainer {\n guard let ctr = self.containers[id] else {\n throw ContainerizationError(\n .notFound,\n message: \"container \\(id) not found\"\n )\n }\n return ctr\n }\n\n func add(container: ManagedContainer) throws {\n guard containers[container.id] == nil else {\n throw ContainerizationError(\n .exists,\n message: \"container \\(container.id) already exists\"\n )\n }\n containers[container.id] = container\n }\n\n func add(proxy: VsockProxy) throws {\n guard proxies[proxy.id] == nil else {\n throw ContainerizationError(\n .exists,\n message: \"proxy \\(proxy.id) already exists\"\n )\n }\n proxies[proxy.id] = proxy\n }\n\n func remove(proxy id: String) throws -> VsockProxy {\n guard let proxy = proxies.removeValue(forKey: id) else {\n throw ContainerizationError(\n .notFound,\n message: \"proxy \\(id) does not exist\"\n )\n }\n return proxy\n }\n\n func remove(container id: String) throws {\n guard let _ = containers.removeValue(forKey: id) else {\n throw ContainerizationError(\n .notFound,\n message: \"container \\(id) does not exist\"\n )\n }\n }\n }\n\n init(log: Logger, group: MultiThreadedEventLoopGroup) {\n self.log = log\n self.group = group\n self.state = State()\n }\n\n func serve(port: Int) async throws {\n try await withThrowingTaskGroup(of: Void.self) { group in\n log.debug(\"starting process supervisor\")\n\n await ProcessSupervisor.default.setLog(self.log)\n await ProcessSupervisor.default.ready()\n\n log.debug(\n \"booting grpc server on vsock\",\n metadata: [\n \"port\": \"\\(port)\"\n ])\n let server = try await Server.start(\n configuration: .default(\n target: .vsockAddress(.init(cid: .any, port: .init(port))),\n eventLoopGroup: self.group,\n serviceProviders: [self])\n ).get()\n log.info(\n \"grpc api serving on vsock\",\n metadata: [\n \"port\": \"\\(port)\"\n ])\n\n group.addTask {\n try await server.onClose.get()\n }\n try await group.next()\n group.cancelAll()\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/LocalOCILayoutClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport Crypto\nimport Foundation\nimport NIOCore\nimport NIOFoundationCompat\n\npackage final class LocalOCILayoutClient: ContentClient {\n let cs: LocalContentStore\n\n package init(root: URL) throws {\n self.cs = try LocalContentStore(path: root)\n }\n\n private func _fetch(digest: String) async throws -> Content {\n guard let c: Content = try await self.cs.get(digest: digest) else {\n throw Error.missingContent(digest)\n }\n return c\n }\n\n package func fetch(name: String, descriptor: Descriptor) async throws -> T {\n let c = try await self._fetch(digest: descriptor.digest)\n return try c.decode()\n }\n\n package func fetchBlob(name: String, descriptor: Descriptor, into file: URL, progress: ProgressHandler?) async throws -> (Int64, SHA256Digest) {\n let c = try await self._fetch(digest: descriptor.digest)\n let fileManager = FileManager.default\n let filePath = file.absolutePath()\n if !fileManager.fileExists(atPath: filePath) {\n let src = c.path\n try fileManager.copyItem(at: src, to: file)\n\n if let progress, let fileSize = fileManager.fileSize(atPath: filePath) {\n await progress([\n ProgressEvent(event: \"add-size\", value: fileSize)\n ])\n }\n }\n let size = try Int64(c.size())\n let digest = try c.digest()\n return (size, digest)\n }\n\n package func fetchData(name: String, descriptor: Descriptor) async throws -> Data {\n let c = try await self._fetch(digest: descriptor.digest)\n return try c.data()\n }\n\n package func push(\n name: String,\n ref: String,\n descriptor: Descriptor,\n streamGenerator: () throws -> T,\n progress: ProgressHandler?\n ) async throws where T.Element == ByteBuffer {\n let input = try streamGenerator()\n\n let (id, dir) = try await self.cs.newIngestSession()\n do {\n let into = dir.appendingPathComponent(descriptor.digest.trimmingDigestPrefix)\n guard FileManager.default.createFile(atPath: into.path, contents: nil) else {\n throw Error.cannotCreateFile\n }\n let fd = try FileHandle(forWritingTo: into)\n defer {\n try? fd.close()\n }\n var wrote = 0\n var hasher = SHA256()\n\n for try await buffer in input {\n wrote += buffer.readableBytes\n try fd.write(contentsOf: buffer.readableBytesView)\n hasher.update(data: buffer.readableBytesView)\n }\n try await self.cs.completeIngestSession(id)\n } catch {\n try await self.cs.cancelIngestSession(id)\n }\n }\n}\n\nextension LocalOCILayoutClient {\n private static let ociLayoutFileName = \"oci-layout\"\n private static let ociLayoutVersionString = \"imageLayoutVersion\"\n private static let ociLayoutIndexFileName = \"index.json\"\n\n package func loadIndexFromOCILayout(directory: URL) throws -> ContainerizationOCI.Index {\n let fm = FileManager.default\n let decoder = JSONDecoder()\n\n let ociLayoutFile = directory.appendingPathComponent(Self.ociLayoutFileName)\n guard fm.fileExists(atPath: ociLayoutFile.absolutePath()) else {\n throw ContainerizationError(.notFound, message: ociLayoutFile.absolutePath())\n }\n var data = try Data(contentsOf: ociLayoutFile)\n let ociLayout = try decoder.decode([String: String].self, from: data)\n guard ociLayout[Self.ociLayoutVersionString] != nil else {\n throw ContainerizationError(.empty, message: \"missing key \\(Self.ociLayoutVersionString) in \\(ociLayoutFile.absolutePath())\")\n }\n\n let indexFile = directory.appendingPathComponent(Self.ociLayoutIndexFileName)\n guard fm.fileExists(atPath: indexFile.absolutePath()) else {\n throw ContainerizationError(.notFound, message: indexFile.absolutePath())\n }\n data = try Data(contentsOf: indexFile)\n let index = try decoder.decode(ContainerizationOCI.Index.self, from: data)\n return index\n }\n\n package func createOCILayoutStructure(directory: URL, manifests: [Descriptor]) throws {\n let fm = FileManager.default\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.withoutEscapingSlashes]\n\n let ingestDir = directory.appendingPathComponent(\"ingest\")\n try? fm.removeItem(at: ingestDir)\n let ociLayoutContent: [String: String] = [\n Self.ociLayoutVersionString: \"1.0.0\"\n ]\n\n var data = try encoder.encode(ociLayoutContent)\n var p = directory.appendingPathComponent(Self.ociLayoutFileName).absolutePath()\n guard fm.createFile(atPath: p, contents: data) else {\n throw ContainerizationError(.internalError, message: \"failed to create file \\(p)\")\n }\n let idx = ContainerizationOCI.Index(schemaVersion: 2, manifests: manifests)\n data = try encoder.encode(idx)\n p = directory.appendingPathComponent(Self.ociLayoutIndexFileName).absolutePath()\n guard fm.createFile(atPath: p, contents: data) else {\n throw ContainerizationError(.internalError, message: \"failed to create file \\(p)\")\n }\n }\n\n package func setImageReferenceAnnotation(descriptor: inout Descriptor, reference: String) {\n var annotations = descriptor.annotations ?? [:]\n annotations[AnnotationKeys.containerizationImageName] = reference\n annotations[AnnotationKeys.containerdImageName] = reference\n annotations[AnnotationKeys.openContainersImageName] = reference\n descriptor.annotations = annotations\n }\n\n package func getImageReferencefromDescriptor(descriptor: Descriptor) -> String? {\n let annotations = descriptor.annotations\n guard let annotations else {\n return nil\n }\n\n // Annotations here do not conform to the OCI image specification.\n // The interpretation of the annotations \"org.opencontainers.image.ref.name\" and\n // \"io.containerd.image.name\" is under debate:\n // - OCI spec examples suggest it should be the image tag:\n // https://github.com/opencontainers/image-spec/blob/fbb4662eb53b80bd38f7597406cf1211317768f0/image-layout.md?plain=1#L175\n // - Buildkitd maintainers argue it should represent the full image name:\n // https://github.com/moby/buildkit/issues/4615#issuecomment-2521810830\n // Until a consensus is reached, the preference is given to \"com.apple.containerization.image.name\" and then to\n // using \"io.containerd.image.name\" as it is the next safest choice\n if let name = annotations[AnnotationKeys.containerizationImageName] {\n return name\n }\n if let name = annotations[AnnotationKeys.containerdImageName] {\n return name\n }\n if let name = annotations[AnnotationKeys.openContainersImageName] {\n return name\n }\n return nil\n }\n\n package enum Error: Swift.Error {\n case missingContent(_ digest: String)\n case unsupportedInput\n case cannotCreateFile\n }\n}\n"], ["/containerization/vminitd/Sources/vmexec/vmexec.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// NOTE: This binary implements a very small subset of the OCI runtime spec, mostly just\n/// the process configurations. Mounts are somewhat functional, but masked and read only paths\n/// aren't checked today. Today the namespaces are also ignored, and we always spawn a new pid\n/// and mount namespace.\n\nimport ArgumentParser\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport LCShim\nimport Logging\nimport Musl\n\n@main\nstruct App: ParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"vmexec\",\n version: \"0.1.0\",\n subcommands: [\n ExecCommand.self,\n RunCommand.self,\n ]\n )\n\n static let standardErrorLock = NSLock()\n\n @Sendable\n static func standardError(label: String) -> StreamLogHandler {\n standardErrorLock.withLock {\n StreamLogHandler.standardError(label: label)\n }\n }\n}\n\nextension App {\n /// Applies O_CLOEXEC to all file descriptors currently open for\n /// the process except the stdio fd values\n static func applyCloseExecOnFDs() throws {\n let minFD = 2 // stdin, stdout, stderr should be preserved\n\n let fdList = try FileManager.default.contentsOfDirectory(atPath: \"/proc/self/fd\")\n\n for fdStr in fdList {\n guard let fd = Int(fdStr) else {\n continue\n }\n if fd <= minFD {\n continue\n }\n\n _ = fcntl(Int32(fd), F_SETFD, FD_CLOEXEC)\n }\n }\n\n static func exec(process: ContainerizationOCI.Process) throws {\n let executable = strdup(process.args[0])\n var argv = process.args.map { strdup($0) }\n argv += [nil]\n\n let env = process.env.map { strdup($0) } + [nil]\n let cwd = process.cwd\n\n // switch cwd\n guard chdir(cwd) == 0 else {\n throw App.Errno(stage: \"chdir(cwd)\", info: \"Failed to change directory to '\\(cwd)'\")\n }\n\n guard execvpe(executable, argv, env) != -1 else {\n throw App.Errno(stage: \"execvpe(\\(String(describing: executable)))\", info: \"Failed to exec [\\(process.args.joined(separator: \" \"))]\")\n }\n fatalError(\"execvpe failed\")\n }\n\n static func setPermissions(user: ContainerizationOCI.User) throws {\n if user.additionalGids.count > 0 {\n guard setgroups(user.additionalGids.count, user.additionalGids) == 0 else {\n throw App.Errno(stage: \"setgroups()\")\n }\n }\n guard setgid(user.gid) == 0 else {\n throw App.Errno(stage: \"setgid()\")\n }\n // NOTE: setuid has to be done last because once the uid has been\n // changed, then the process will lose privilege to set the group\n // and supplementary groups\n guard setuid(user.uid) == 0 else {\n throw App.Errno(stage: \"setuid()\")\n }\n }\n\n static func fixStdioPerms(user: ContainerizationOCI.User) throws {\n for i in 0...2 {\n var fdStat = stat()\n try withUnsafeMutablePointer(to: &fdStat) { pointer in\n guard fstat(Int32(i), pointer) == 0 else {\n throw App.Errno(stage: \"fstat(fd)\")\n }\n }\n\n let desired = uid_t(user.uid)\n if fdStat.st_uid != desired {\n guard fchown(Int32(i), desired, fdStat.st_gid) != -1 else {\n throw App.Errno(stage: \"fchown(\\(i))\")\n }\n }\n }\n }\n\n static func setRLimits(rlimits: [ContainerizationOCI.POSIXRlimit]) throws {\n for rl in rlimits {\n var limit = rlimit(rlim_cur: rl.soft, rlim_max: rl.hard)\n let resource: Int32\n switch rl.type {\n case \"RLIMIT_AS\":\n resource = RLIMIT_AS\n case \"RLIMIT_CORE\":\n resource = RLIMIT_CORE\n case \"RLIMIT_CPU\":\n resource = RLIMIT_CPU\n case \"RLIMIT_DATA\":\n resource = RLIMIT_DATA\n case \"RLIMIT_FSIZE\":\n resource = RLIMIT_FSIZE\n case \"RLIMIT_NOFILE\":\n resource = RLIMIT_NOFILE\n case \"RLIMIT_STACK\":\n resource = RLIMIT_STACK\n case \"RLIMIT_NPROC\":\n resource = RLIMIT_NPROC\n case \"RLIMIT_RSS\":\n resource = RLIMIT_RSS\n case \"RLIMIT_MEMLOCK\":\n resource = RLIMIT_MEMLOCK\n default:\n errno = EINVAL\n throw App.Errno(stage: \"rlimit key unknown\")\n }\n guard setrlimit(resource, &limit) == 0 else {\n throw App.Errno(stage: \"setrlimit()\")\n }\n }\n }\n\n static func Errno(stage: String, info: String = \"\") -> ContainerizationError {\n let posix = POSIXError(.init(rawValue: errno)!, userInfo: [\"stage\": stage])\n return ContainerizationError(.internalError, message: \"\\(info) \\(String(describing: posix))\")\n }\n}\n"], ["/containerization/vminitd/Sources/vmexec/ExecCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerizationOCI\nimport Foundation\nimport LCShim\nimport Logging\nimport Musl\n\nstruct ExecCommand: ParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"exec\",\n abstract: \"Exec in a container\"\n )\n\n @Option(name: .long, help: \"path to an OCI runtime spec process configuration\")\n var processPath: String\n\n @Option(name: .long, help: \"pid of the init process for the container\")\n var parentPid: Int\n\n func run() throws {\n LoggingSystem.bootstrap(App.standardError)\n let log = Logger(label: \"vmexec\")\n\n let src = URL(fileURLWithPath: processPath)\n let processBytes = try Data(contentsOf: src)\n let process = try JSONDecoder().decode(\n ContainerizationOCI.Process.self,\n from: processBytes\n )\n try execInNamespaces(process: process, log: log)\n }\n\n static func enterNS(path: String, nsType: Int32) throws {\n let fd = open(path, O_RDONLY)\n if fd <= 0 {\n throw App.Errno(stage: \"open(ns)\")\n }\n defer { close(fd) }\n\n guard setns(fd, nsType) == 0 else {\n throw App.Errno(stage: \"setns(fd)\")\n }\n }\n\n private func execInNamespaces(\n process: ContainerizationOCI.Process,\n log: Logger\n ) throws {\n // CLOEXEC the pipe fd that signals process readiness.\n let syncfd = FileHandle(fileDescriptor: 3)\n if fcntl(3, F_SETFD, FD_CLOEXEC) == -1 {\n throw App.Errno(stage: \"cloexec(syncfd)\")\n }\n\n try Self.enterNS(path: \"/proc/\\(self.parentPid)/ns/cgroup\", nsType: CLONE_NEWCGROUP)\n try Self.enterNS(path: \"/proc/\\(self.parentPid)/ns/pid\", nsType: CLONE_NEWPID)\n try Self.enterNS(path: \"/proc/\\(self.parentPid)/ns/uts\", nsType: CLONE_NEWUTS)\n try Self.enterNS(path: \"/proc/\\(self.parentPid)/ns/mnt\", nsType: CLONE_NEWNS)\n\n let childPipe = Pipe()\n try childPipe.setCloexec()\n let processID = fork()\n\n guard processID != -1 else {\n try? childPipe.fileHandleForReading.close()\n try? childPipe.fileHandleForWriting.close()\n try? syncfd.close()\n\n throw App.Errno(stage: \"fork\")\n }\n\n if processID == 0 { // child\n try childPipe.fileHandleForReading.close()\n try syncfd.close()\n\n guard setsid() != -1 else {\n throw App.Errno(stage: \"setsid()\")\n }\n\n // Apply O_CLOEXEC to all file descriptors except stdio.\n // This ensures that all unwanted fds we may have accidentally\n // inherited are marked close-on-exec so they stay out of the\n // container.\n try App.applyCloseExecOnFDs()\n try App.setRLimits(rlimits: process.rlimits)\n\n // Change stdio to be owned by the requested user.\n try App.fixStdioPerms(user: process.user)\n\n // Set uid, gid, and supplementary groups\n try App.setPermissions(user: process.user)\n\n if process.terminal {\n guard ioctl(0, UInt(TIOCSCTTY), 0) != -1 else {\n throw App.Errno(stage: \"setctty()\")\n }\n }\n\n try App.exec(process: process)\n } else { // parent process\n try childPipe.fileHandleForWriting.close()\n\n // wait until the pipe is closed then carry on.\n _ = try childPipe.fileHandleForReading.readToEnd()\n try childPipe.fileHandleForReading.close()\n\n // send our child's pid to our parent before we exit.\n var childPid = processID\n let data = Data(bytes: &childPid, count: MemoryLayout.size(ofValue: childPid))\n\n try syncfd.write(contentsOf: data)\n try syncfd.close()\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/RegistryClient+Push.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport NIO\n\nextension RegistryClient {\n /// Pushes the content specified by a descriptor to a remote registry.\n /// - Parameters:\n /// - name: The namespace which the descriptor should belong under.\n /// - tag: The tag or digest for uniquely identifying the manifest.\n /// By convention, any portion that may be a partial or whole digest\n /// will be proceeded by an `@`. Anything preceding the `@` will be referred\n /// to as \"tag\".\n /// This is usually broken down into the following possibilities:\n /// 1. \n /// 2. @\n /// 3. @\n /// The tag is anything except `@` and `:`, and digest is anything after the `@`\n /// - descriptor: The OCI descriptor of the content to be pushed.\n /// - streamGenerator: A closure that produces an`AsyncStream` of `ByteBuffer`\n /// for streaming data to the `HTTPClientRequest.Body`.\n /// The caller is responsible for providing the `AsyncStream` where the data may come from\n /// a file on disk, data in memory, etc.\n /// - progress: The progress handler to invoke as data is sent.\n public func push(\n name: String,\n ref tag: String,\n descriptor: Descriptor,\n streamGenerator: () throws -> T,\n progress: ProgressHandler?\n ) async throws where T.Element == ByteBuffer {\n var components = base\n\n let mediaType = descriptor.mediaType\n if mediaType.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Missing media type for descriptor \\(descriptor.digest)\")\n }\n\n var isManifest = false\n var existCheck: [String] = []\n\n switch mediaType {\n case MediaTypes.dockerManifest, MediaTypes.dockerManifestList, MediaTypes.imageManifest, MediaTypes.index:\n isManifest = true\n existCheck = self.getManifestPath(tag: tag, digest: descriptor.digest)\n default:\n existCheck = [\"blobs\", descriptor.digest]\n }\n\n // Check if the content already exists.\n components.path = \"/v2/\\(name)/\\(existCheck.joined(separator: \"/\"))\"\n\n let mediaTypes = [\n mediaType,\n \"*/*\",\n ]\n\n var headers = [\n (\"Accept\", mediaTypes.joined(separator: \", \"))\n ]\n\n try await request(components: components, method: .HEAD, headers: headers) { response in\n if response.status == .ok {\n var exists = false\n if isManifest && existCheck[1] != descriptor.digest {\n if descriptor.digest == response.headers.first(name: \"Docker-Content-Digest\") {\n exists = true\n }\n } else {\n exists = true\n }\n\n if exists {\n throw ContainerizationError(.exists, message: \"Content already exists \\(descriptor.digest)\")\n }\n } else if response.status != .notFound {\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n }\n\n if isManifest {\n let path = self.getManifestPath(tag: tag, digest: descriptor.digest)\n components.path = \"/v2/\\(name)/\\(path.joined(separator: \"/\"))\"\n headers = [\n (\"Content-Type\", mediaType)\n ]\n } else {\n // Start upload request for blobs.\n components.path = \"/v2/\\(name)/blobs/uploads/\"\n try await request(components: components, method: .POST) { response in\n switch response.status {\n case .ok, .accepted, .noContent:\n break\n case .created:\n throw ContainerizationError(.exists, message: \"Content already exists \\(descriptor.digest)\")\n default:\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n\n // Get the location to upload the blob.\n guard let location = response.headers.first(name: \"Location\") else {\n throw ContainerizationError(.invalidArgument, message: \"Missing required header Location\")\n }\n\n guard let urlComponents = URLComponents(string: location) else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid url \\(location)\")\n }\n var queryItems = urlComponents.queryItems ?? []\n queryItems.append(URLQueryItem(name: \"digest\", value: descriptor.digest))\n components.path = urlComponents.path\n components.queryItems = queryItems\n headers = [\n (\"Content-Type\", \"application/octet-stream\"),\n (\"Content-Length\", String(descriptor.size)),\n ]\n }\n }\n\n // We have to pass a body closure rather than a body to reset the stream when retrying.\n let bodyClosure = {\n let stream = try streamGenerator()\n let body = HTTPClientRequest.Body.stream(stream, length: .known(descriptor.size))\n return body\n }\n\n return try await request(components: components, method: .PUT, bodyClosure: bodyClosure, headers: headers) { response in\n switch response.status {\n case .ok, .created, .noContent:\n break\n default:\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n\n guard descriptor.digest == response.headers.first(name: \"Docker-Content-Digest\") else {\n let required = response.headers.first(name: \"Docker-Content-Digest\") ?? \"\"\n throw ContainerizationError(.internalError, message: \"Digest mismatch \\(descriptor.digest) != \\(required)\")\n }\n }\n }\n\n private func getManifestPath(tag: String, digest: String) -> [String] {\n var object = tag\n if let i = tag.firstIndex(of: \"@\") {\n let index = tag.index(after: i)\n if String(tag[index...]) != digest {\n object = \"\"\n } else {\n object = String(tag[...i])\n }\n }\n\n if object == \"\" {\n return [\"manifests\", digest]\n }\n\n return [\"manifests\", object]\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4Reader+Export.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationArchive\nimport Foundation\nimport SystemPackage\n\nextension EXT4.EXT4Reader {\n public func export(archive: FilePath) throws {\n let config = ArchiveWriterConfiguration(\n format: .paxRestricted, filter: .none, options: [Options.xattrformat(.schily)])\n let writer = try ArchiveWriter(configuration: config)\n try writer.open(file: archive.url)\n var items = self.tree.root.pointee.children\n let hardlinkedInodes = Set(self.hardlinks.values)\n var hardlinkTargets: [EXT4.InodeNumber: FilePath] = [:]\n\n while items.count > 0 {\n let itemPtr = items.removeFirst()\n let item = itemPtr.pointee\n let inode = try self.getInode(number: item.inode)\n let entry = WriteEntry()\n let mode = inode.mode\n let size: UInt64 = (UInt64(inode.sizeHigh) << 32) | UInt64(inode.sizeLow)\n entry.permissions = mode\n guard let path = item.path else {\n continue\n }\n if hardlinkedInodes.contains(item.inode) {\n hardlinkTargets[item.inode] = path\n }\n guard self.hardlinks[path] == nil else {\n continue\n }\n var attributes: [EXT4.ExtendedAttribute] = []\n let buffer: [UInt8] = EXT4.tupleToArray(inode.inlineXattrs)\n if !buffer.allZeros {\n try attributes.append(contentsOf: Self.readInlineExtendedAttributes(from: buffer))\n }\n if inode.xattrBlockLow != 0 {\n let block = inode.xattrBlockLow\n try self.seek(block: block)\n guard let buffer = try self.handle.read(upToCount: Int(self.blockSize)) else {\n throw EXT4.Error.couldNotReadBlock(block)\n }\n try attributes.append(contentsOf: Self.readBlockExtendedAttributes(from: [UInt8](buffer)))\n }\n\n var xattrs: [String: Data] = [:]\n for attribute in attributes {\n guard attribute.fullName != \"system.data\" else {\n continue\n }\n xattrs[attribute.fullName] = Data(attribute.value)\n }\n\n let pathStr = path.description\n entry.path = pathStr\n entry.size = Int64(size)\n entry.group = gid_t(inode.gid)\n entry.owner = uid_t(inode.uid)\n entry.creationDate = Date(fsTimestamp: UInt64((inode.ctimeExtra << 32) | inode.ctime))\n entry.modificationDate = Date(fsTimestamp: UInt64((inode.mtimeExtra << 32) | inode.mtime))\n entry.contentAccessDate = Date(fsTimestamp: UInt64((inode.atimeExtra << 32) | inode.atime))\n entry.xattrs = xattrs\n\n if mode.isDir() {\n entry.fileType = .directory\n for child in item.children {\n items.append(child)\n }\n if pathStr == \"\" {\n continue\n }\n try writer.writeEntry(entry: entry, data: nil)\n } else if mode.isReg() {\n entry.fileType = .regular\n var data = Data()\n var remaining: UInt64 = size\n if let block = item.blocks {\n for dataBlock in block.start.. self.blockSize {\n count = self.blockSize\n } else {\n count = remaining\n }\n guard let dataBytes = try self.handle.read(upToCount: Int(count)) else {\n throw EXT4.Error.couldNotReadBlock(dataBlock)\n }\n data.append(dataBytes)\n remaining -= UInt64(dataBytes.count)\n }\n }\n if let additionalBlocks = item.additionalBlocks {\n for block in additionalBlocks {\n for dataBlock in block.start.. self.blockSize {\n count = self.blockSize\n } else {\n count = remaining\n }\n guard let dataBytes = try self.handle.read(upToCount: Int(count)) else {\n throw EXT4.Error.couldNotReadBlock(dataBlock)\n }\n data.append(dataBytes)\n remaining -= UInt64(dataBytes.count)\n }\n }\n }\n try writer.writeEntry(entry: entry, data: data)\n } else if mode.isLink() {\n entry.fileType = .symbolicLink\n if size < 60 {\n let linkBytes = EXT4.tupleToArray(inode.block)\n entry.symlinkTarget = String(bytes: linkBytes, encoding: .utf8) ?? \"\"\n } else {\n if let block = item.blocks {\n try self.seek(block: block.start)\n guard let linkBytes = try self.handle.read(upToCount: Int(size)) else {\n throw EXT4.Error.couldNotReadBlock(block.start)\n }\n entry.symlinkTarget = String(bytes: linkBytes, encoding: .utf8) ?? \"\"\n }\n }\n try writer.writeEntry(entry: entry, data: nil)\n } else { // do not process sockets, fifo, character and block devices\n continue\n }\n }\n for (path, number) in self.hardlinks {\n guard let targetPath = hardlinkTargets[number] else {\n continue\n }\n let inode = try self.getInode(number: number)\n let entry = WriteEntry()\n entry.path = path.description\n entry.hardlink = targetPath.description\n entry.permissions = inode.mode\n entry.group = gid_t(inode.gid)\n entry.owner = uid_t(inode.uid)\n entry.creationDate = Date(fsTimestamp: UInt64((inode.ctimeExtra << 32) | inode.ctime))\n entry.modificationDate = Date(fsTimestamp: UInt64((inode.mtimeExtra << 32) | inode.mtime))\n entry.contentAccessDate = Date(fsTimestamp: UInt64((inode.atimeExtra << 32) | inode.atime))\n try writer.writeEntry(entry: entry, data: nil)\n }\n try writer.finishEncoding()\n }\n\n @available(*, deprecated, renamed: \"readInlineExtendedAttributes(from:)\")\n public static func readInlineExtenedAttributes(from buffer: [UInt8]) throws -> [EXT4.ExtendedAttribute] {\n try readInlineExtendedAttributes(from: buffer)\n }\n\n public static func readInlineExtendedAttributes(from buffer: [UInt8]) throws -> [EXT4.ExtendedAttribute] {\n let header = UInt32(littleEndian: buffer[0...4].withUnsafeBytes { $0.load(as: UInt32.self) })\n if header != EXT4.XAttrHeaderMagic {\n throw EXT4.FileXattrsState.Error.missingXAttrHeader\n }\n return try EXT4.FileXattrsState.read(buffer: buffer, start: 4, offset: 4)\n }\n\n @available(*, deprecated, renamed: \"readBlockExtendedAttributes(from:)\")\n public static func readBlockExtenedAttributes(from buffer: [UInt8]) throws -> [EXT4.ExtendedAttribute] {\n try readBlockExtendedAttributes(from: buffer)\n }\n\n public static func readBlockExtendedAttributes(from buffer: [UInt8]) throws -> [EXT4.ExtendedAttribute] {\n let header = UInt32(littleEndian: buffer[0...4].withUnsafeBytes { $0.load(as: UInt32.self) })\n if header != EXT4.XAttrHeaderMagic {\n throw EXT4.FileXattrsState.Error.missingXAttrHeader\n }\n\n return try EXT4.FileXattrsState.read(buffer: [UInt8](buffer), start: 32, offset: 0)\n }\n\n func seek(block: UInt32) throws {\n try self.handle.seek(toOffset: UInt64(block) * blockSize)\n }\n}\n\nextension Date {\n init(fsTimestamp: UInt64) {\n if fsTimestamp == 0 {\n self = Date.distantPast\n return\n }\n\n let seconds = Int64(fsTimestamp & 0x3_ffff_ffff)\n let nanoseconds = Double(fsTimestamp >> 34) / 1_000_000_000\n\n self = Date(timeIntervalSince1970: Double(seconds) + nanoseconds)\n }\n}\n#endif\n"], ["/containerization/Sources/cctl/ImageCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\nextension Application {\n struct Images: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"images\",\n abstract: \"Manage images\",\n subcommands: [\n Get.self,\n Delete.self,\n Pull.self,\n Tag.self,\n Push.self,\n Save.self,\n Load.self,\n ]\n )\n\n func run() async throws {\n let store = Application.imageStore\n let images = try await store.list()\n\n print(\"REFERENCE\\tMEDIA TYPE\\tDIGEST\")\n for image in images {\n print(\"\\(image.reference)\\t\\(image.mediaType)\\t\\(image.digest)\")\n }\n }\n\n struct Delete: AsyncParsableCommand {\n @Argument var reference: String\n\n func run() async throws {\n let store = Application.imageStore\n try await store.delete(reference: reference)\n }\n }\n\n struct Tag: AsyncParsableCommand {\n @Argument var old: String\n @Argument var new: String\n\n func run() async throws {\n let store = Application.imageStore\n _ = try await store.tag(existing: old, new: new)\n }\n }\n\n struct Get: AsyncParsableCommand {\n @Argument var reference: String\n\n func run() async throws {\n let store = Application.imageStore\n let image = try await store.get(reference: reference)\n\n let index = try await image.index()\n\n let enc = JSONEncoder()\n enc.outputFormatting = .prettyPrinted\n let data = try enc.encode(ImageDisplay(reference: image.reference, index: index))\n print(String(data: data, encoding: .utf8)!)\n }\n }\n\n struct ImageDisplay: Codable {\n let reference: String\n let index: Index\n }\n\n struct Pull: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"pull\",\n abstract: \"Pull an image's contents into a content store\"\n )\n\n @Argument var ref: String\n\n @Option(name: .customLong(\"platform\"), help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platformString: String?\n\n @Option(\n name: .customLong(\"unpack-path\"), help: \"Path to a new directory to unpack the image into\",\n transform: { str in\n URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)\n })\n var unpackPath: String?\n\n @Flag(help: \"Pull via plain text http\") var http: Bool = false\n\n func run() async throws {\n let imageStore = Application.imageStore\n let platform: Platform? = try {\n if let platformString {\n return try Platform(from: platformString)\n }\n return nil\n }()\n\n let reference = try Reference.parse(ref)\n reference.normalize()\n let normalizedReference = reference.description\n if normalizedReference != ref {\n print(\"Reference resolved to \\(reference.description)\")\n }\n\n let image = try await Images.withAuthentication(ref: normalizedReference) { auth in\n try await imageStore.pull(reference: normalizedReference, platform: platform, insecure: http, auth: auth)\n }\n\n guard let image else {\n print(\"image pull failed\")\n Application.exit(withError: POSIXError(.EACCES))\n }\n\n print(\"image pulled\")\n guard let unpackPath else {\n return\n }\n guard !FileManager.default.fileExists(atPath: unpackPath) else {\n throw ContainerizationError(.exists, message: \"Directory already exists at \\(unpackPath)\")\n }\n let unpackUrl = URL(filePath: unpackPath)\n try FileManager.default.createDirectory(at: unpackUrl, withIntermediateDirectories: true)\n\n let unpacker = EXT4Unpacker.init(blockSizeInBytes: 2.gib())\n\n if let platform {\n let name = platform.description.replacingOccurrences(of: \"/\", with: \"-\")\n let _ = try await unpacker.unpack(image, for: platform, at: unpackUrl.appending(component: name))\n } else {\n for descriptor in try await image.index().manifests {\n if let referenceType = descriptor.annotations?[\"vnd.docker.reference.type\"], referenceType == \"attestation-manifest\" {\n continue\n }\n guard let descPlatform = descriptor.platform else {\n continue\n }\n let name = descPlatform.description.replacingOccurrences(of: \"/\", with: \"-\")\n let _ = try await unpacker.unpack(image, for: descPlatform, at: unpackUrl.appending(component: name))\n print(\"created snapshot for platform \\(descPlatform.description)\")\n }\n }\n }\n }\n\n struct Push: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"push\",\n abstract: \"Push an image to a remote registry\"\n )\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platformString: String?\n\n @Flag(help: \"Push via plain text http\") var http: Bool = false\n\n @Argument var ref: String\n\n func run() async throws {\n let imageStore = Application.imageStore\n let platform: Platform? = try {\n if let platformString {\n return try Platform(from: platformString)\n }\n return nil\n }()\n\n let reference = try Reference.parse(ref)\n reference.normalize()\n let normalizedReference = reference.description\n if normalizedReference != ref {\n print(\"Reference resolved to \\(reference.description)\")\n }\n\n try await Images.withAuthentication(ref: normalizedReference) { auth in\n try await imageStore.push(reference: normalizedReference, platform: platform, insecure: http, auth: auth)\n }\n print(\"image pushed\")\n }\n }\n\n struct Save: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"save\",\n abstract: \"Save one or more images to a tar archive\"\n )\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platform: String?\n\n @Option(name: .shortAndLong, help: \"Path to tar archive\")\n var output: String\n\n @Argument var reference: [String]\n\n func run() async throws {\n var p: Platform? = nil\n if let platform {\n p = try Platform(from: platform)\n }\n let store = Application.imageStore\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n try await store.save(references: reference, out: tempDir, platform: p)\n let writer = try ArchiveWriter(format: .pax, filter: .none, file: URL(filePath: output))\n try writer.archiveDirectory(tempDir)\n try writer.finishEncoding()\n print(\"image exported\")\n }\n }\n\n struct Load: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"load\",\n abstract: \"Load one or more images from a tar archive\"\n )\n\n @Option(name: .shortAndLong, help: \"Path to tar archive\")\n var input: String\n\n func run() async throws {\n let store = Application.imageStore\n let tarFile = URL(fileURLWithPath: input)\n let reader = try ArchiveReader(file: tarFile.absoluteURL)\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n try reader.extractContents(to: tempDir)\n let imported = try await store.load(from: tempDir)\n for image in imported {\n print(\"imported \\(image.reference)\")\n }\n }\n }\n\n private static func withAuthentication(\n ref: String, _ body: @Sendable @escaping (_ auth: Authentication?) async throws -> T?\n ) async throws -> T? {\n var authentication: Authentication?\n let ref = try Reference.parse(ref)\n guard let host = ref.resolvedDomain else {\n throw ContainerizationError(.invalidArgument, message: \"No host specified in image reference\")\n }\n authentication = Self.authenticationFromEnv(host: host)\n if let authentication {\n return try await body(authentication)\n }\n let keychain = KeychainHelper(id: Application.keychainID)\n authentication = try? keychain.lookup(domain: host)\n return try await body(authentication)\n }\n\n private static func authenticationFromEnv(host: String) -> Authentication? {\n let env = ProcessInfo.processInfo.environment\n guard env[\"REGISTRY_HOST\"] == host else {\n return nil\n }\n guard let user = env[\"REGISTRY_USERNAME\"], let password = env[\"REGISTRY_TOKEN\"] else {\n return nil\n }\n return BasicAuthentication(username: user, password: password)\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Xattrs.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/*\n * Note: Both the entries and values for the attributes need to occupy a size that is a multiple of 4,\n * meaning, in cases where the attribute name or value is less than not a multiple of 4, it is padded with 0\n * until it reaches that size.\n */\n\nextension EXT4 {\n public struct ExtendedAttribute {\n public static let prefixMap: [Int: String] = [\n 1: \"user.\",\n 2: \"system.posix_acl_access\",\n 3: \"system.posix_acl_default\",\n 4: \"trusted.\",\n 6: \"security.\",\n 7: \"system.\",\n 8: \"system.richacl\",\n ]\n\n let name: String\n let index: UInt8\n let value: [UInt8]\n\n var sizeValue: UInt32 {\n UInt32((value.count + 3) & ~3)\n }\n\n var sizeEntry: UInt32 {\n UInt32((name.count + 3) & ~3 + 16) // 16 bytes are needed to store other metadata for the xattr entry\n }\n\n var size: UInt32 {\n sizeEntry + sizeValue\n }\n\n var fullName: String {\n Self.decompressName(id: Int(index), suffix: name)\n }\n\n var hash: UInt32 {\n var hash: UInt32 = 0\n for char in name {\n hash = (hash << 5) ^ (hash >> 27) ^ UInt32(char.asciiValue!)\n }\n var i = 0\n while i + 3 < value.count {\n let s = value[i..> 16) ^ v\n i += 4\n }\n if value.count % 4 != 0 {\n let last = value.count & ~3\n var buff: [UInt8] = [0, 0, 0, 0]\n for (i, byte) in value[last...].enumerated() {\n buff[i] = byte\n }\n let v = UInt32(littleEndian: buff.withUnsafeBytes { $0.load(as: UInt32.self) })\n hash = (hash << 16) ^ (hash >> 16) ^ v\n }\n return hash\n }\n\n init(name: String, value: [UInt8]) {\n let compressed = Self.compressName(name)\n self.name = compressed.str\n self.index = compressed.id\n self.value = value\n }\n\n init(idx: UInt8, compressedName name: String, value: [UInt8]) {\n self.name = name\n self.index = idx\n self.value = value\n }\n\n // MARK: Class methods\n public static func compressName(_ name: String) -> (id: UInt8, str: String) {\n for (id, prefix) in prefixMap.sorted(by: { $1.1.count < $0.1.count }) where name.hasPrefix(prefix) {\n return (UInt8(id), String(name.dropFirst(prefix.count)))\n }\n return (0, name)\n }\n\n public static func decompressName(id: Int, suffix: String) -> String {\n guard let prefix = prefixMap[id] else {\n return suffix\n }\n return \"\\(prefix)\\(suffix)\"\n }\n }\n\n public struct FileXattrsState {\n private let inodeCapacity: UInt32\n private let blockCapacity: UInt32\n private let inode: UInt32 // the inode number for which we are tracking these xattrs\n\n var inlineAttributes: [ExtendedAttribute] = []\n var blockAttributes: [ExtendedAttribute] = []\n private var usedSizeInline: UInt32 = 0\n private var usedSizeBlock: UInt32 = 0\n\n private var inodeFreeBytes: UInt32 {\n self.inodeCapacity - EXT4.XattrInodeHeaderSize - usedSizeInline - 4 // need to have 4 null bytes b/w xattr entries and values\n }\n\n private var blockFreeBytes: UInt32 {\n self.blockCapacity - EXT4.XattrBlockHeaderSize - usedSizeBlock - 4\n }\n\n init(inode: UInt32, inodeXattrCapacity: UInt32, blockCapacity: UInt32) {\n self.inode = inode\n self.inodeCapacity = inodeXattrCapacity\n self.blockCapacity = blockCapacity\n }\n\n public mutating func add(_ attribute: ExtendedAttribute) throws {\n let size = attribute.size\n if size <= inodeFreeBytes {\n usedSizeInline += size\n inlineAttributes.append(attribute)\n return\n }\n if size <= blockFreeBytes {\n usedSizeBlock += size\n blockAttributes.append(attribute)\n return\n }\n throw Error.insufficientSpace(Int(self.inode))\n }\n\n public func writeInlineAttributes(buffer: inout [UInt8]) throws {\n var idx = 0\n withUnsafeLittleEndianBytes(\n of: EXT4.XAttrHeaderMagic,\n body: { bytes in\n for byte in bytes {\n buffer[idx] = byte\n idx += 1\n }\n })\n try Self.write(buffer: &buffer, attrs: self.inlineAttributes, start: UInt16(idx), delta: 0, inline: true)\n }\n\n public func writeBlockAttributes(buffer: inout [UInt8]) throws {\n var idx = 0\n for val in [EXT4.XAttrHeaderMagic, 1, 1] {\n withUnsafeLittleEndianBytes(\n of: UInt32(val),\n body: { bytes in\n for byte in bytes {\n buffer[idx] = byte\n idx += 1\n }\n })\n }\n while idx != 32 {\n buffer[idx] = 0\n idx += 1\n }\n var attributes = self.blockAttributes\n attributes.sort(by: {\n if ($0.index < $1.index) || ($0.name.count < $1.name.count) || ($0.name < $1.name) {\n return true\n }\n return false\n })\n try Self.write(buffer: &buffer, attrs: attributes, start: UInt16(idx), delta: UInt16(idx), inline: false)\n }\n\n /// Writes the specified list of extended attribute entries and their values to the provided\n /// This method does not fill in any headers (Inode inline / block level) that may be required to parse these attributes\n ///\n /// - Parameters:\n /// - buffer: An array of [UInt8] where the data will be written into\n /// - attrs: The list of ExtendedAttributes to write\n /// - start: the index from where data should be put into the buffer - useful when if you dont want this method to be overwriting existing data\n /// - delta: index from where the begin the offset calculations\n /// - inline: if the byte buffer being written into is an inline data block for an inode: Determines the hash calculation\n private static func write(\n buffer: inout [UInt8], attrs: [ExtendedAttribute], start: UInt16, delta: UInt16, inline: Bool\n ) throws {\n var offset: UInt16 = UInt16(buffer.count) + delta - start\n var front = Int(start)\n var end = buffer.count\n\n for attribute in attrs {\n guard end - front >= 4 else {\n throw Error.malformedXattrBuffer\n }\n\n var out: [UInt8] = []\n let v = attribute.sizeValue\n offset -= UInt16(v)\n out.append(UInt8(attribute.name.count))\n out.append(attribute.index)\n withUnsafeLittleEndianBytes(\n of: UInt16(offset),\n body: { bytes in\n out.append(contentsOf: bytes)\n })\n out.append(contentsOf: [0, 0, 0, 0]) // these next four bytes indicate that the attr values are in the same block\n withUnsafeLittleEndianBytes(\n of: UInt32(attribute.value.count),\n body: { bytes in\n out.append(contentsOf: bytes)\n })\n if !inline {\n withUnsafeLittleEndianBytes(\n of: UInt32(attribute.hash),\n body: { bytes in\n out.append(contentsOf: bytes)\n })\n } else {\n out.append(contentsOf: [0, 0, 0, 0])\n }\n guard let name = attribute.name.data(using: .ascii) else {\n throw Error.convertAsciiString(attribute.name)\n }\n out.append(contentsOf: [UInt8](name))\n while out.count < Int(attribute.sizeEntry) { // ensure that xattr entry size is a multiple of 4\n out.append(0)\n }\n for (i, byte) in out.enumerated() {\n buffer[front + i] = byte\n }\n front += out.count\n\n end -= Int(attribute.sizeValue)\n for (i, byte) in attribute.value.enumerated() {\n buffer[end + i] = byte\n }\n }\n }\n\n public static func read(buffer: [UInt8], start: Int, offset: Int) throws -> [ExtendedAttribute] {\n var i = start\n var attribs: [ExtendedAttribute] = []\n // 16 is the size of 1 XAttrEntry\n while i + 16 < buffer.count {\n let attributeStart = i\n let rawXattrEntry = Array(buffer[i...size)\n }\n\n public init(blockDevice: FilePath) throws {\n guard FileManager.default.fileExists(atPath: blockDevice.description) else {\n throw EXT4.Error.notFound(blockDevice.description)\n }\n\n guard let fileHandle = FileHandle(forReadingAtPath: blockDevice) else {\n throw Error.notFound(blockDevice.description)\n }\n self.handle = fileHandle\n try handle.seek(toOffset: EXT4.SuperBlockOffset)\n\n let superBlockSize = MemoryLayout.size\n guard let data = try? self.handle.read(upToCount: superBlockSize) else {\n throw EXT4.Error.couldNotReadSuperBlock(blockDevice.description, EXT4.SuperBlockOffset, superBlockSize)\n }\n let sb = data.withUnsafeBytes { ptr in\n ptr.loadLittleEndian(as: EXT4.SuperBlock.self)\n }\n guard sb.magic == EXT4.SuperBlockMagic else {\n throw EXT4.Error.invalidSuperBlock\n }\n self._superBlock = sb\n var items: [(item: Ptr, inode: InodeNumber)] = [\n (self.tree.root, EXT4.RootInode)\n ]\n while items.count > 0 {\n guard let item = items.popLast() else {\n break\n }\n let (itemPtr, inodeNum) = item\n let childItems = try self.children(of: inodeNum)\n let root = itemPtr.pointee\n for (itemName, itemInodeNum) in childItems {\n if itemName == \".\" || itemName == \"..\" {\n continue\n }\n\n if self.inodes[itemInodeNum] != nil {\n // we have seen this inode before, we will hard link this file to it\n guard let parentPath = itemPtr.pointee.path else {\n continue\n }\n let path = parentPath.join(itemName)\n self.hardlinks[path] = itemInodeNum\n continue\n }\n\n let blocks = try self.getExtents(inode: itemInodeNum)\n let itemTreeNodePtr = Ptr.allocate(capacity: 1)\n let itemTreeNode = FileTree.FileTreeNode(\n inode: itemInodeNum,\n name: itemName,\n parent: itemPtr,\n children: []\n )\n if let blocks {\n if blocks.count > 1 {\n itemTreeNode.additionalBlocks = Array(blocks.dropFirst())\n }\n itemTreeNode.blocks = blocks.first\n }\n itemTreeNodePtr.initialize(to: itemTreeNode)\n root.children.append(itemTreeNodePtr)\n itemPtr.initialize(to: root)\n let itemInode = try self.getInode(number: itemInodeNum)\n if itemInode.mode.isDir() {\n items.append((itemTreeNodePtr, itemInodeNum))\n }\n }\n }\n }\n\n deinit {\n try? self.handle.close()\n }\n\n private func readGroupDescriptor(_ number: UInt32) throws -> GroupDescriptor {\n let bs = UInt64(1024 * (1 << _superBlock.logBlockSize))\n let offset = bs + UInt64(number) * UInt64(self.groupDescriptorSize)\n try self.handle.seek(toOffset: offset)\n guard let data = try? self.handle.read(upToCount: MemoryLayout.size) else {\n throw EXT4.Error.couldNotReadGroup(number)\n }\n let gd = data.withUnsafeBytes { ptr in\n ptr.loadLittleEndian(as: EXT4.GroupDescriptor.self)\n }\n return gd\n }\n\n private func readInode(_ number: UInt32) throws -> Inode {\n let inodeGroupNumber = ((number - 1) / self._superBlock.inodesPerGroup)\n let numberInGroup = UInt64((number - 1) % self._superBlock.inodesPerGroup)\n\n let gd = try getGroupDescriptor(inodeGroupNumber)\n let inodeTableStart = UInt64(gd.inodeTableLow) * self.blockSize\n\n let inodeOffset: UInt64 = inodeTableStart + numberInGroup * UInt64(_superBlock.inodeSize)\n try self.handle.seek(toOffset: inodeOffset)\n guard let inodeData = try self.handle.read(upToCount: MemoryLayout.size) else {\n throw EXT4.Error.couldNotReadInode(number)\n }\n let inode = inodeData.withUnsafeBytes { ptr in\n ptr.loadLittleEndian(as: EXT4.Inode.self)\n }\n return inode\n }\n\n private func getDirTree(_ number: InodeNumber) throws -> [(String, InodeNumber)] {\n var children: [(String, InodeNumber)] = []\n let extents = try getExtents(inode: number) ?? []\n for (start, end) in extents {\n try self.seek(block: start)\n for i in 0..<(end - start) {\n guard let dirEntryBlock = try self.handle.read(upToCount: Int(self.blockSize)) else {\n throw EXT4.Error.couldNotReadBlock(start + i)\n }\n let childEntries = try getDirEntries(dirTree: dirEntryBlock)\n children.append(contentsOf: childEntries)\n }\n }\n return children.sorted { a, b in\n a.0 < b.0\n }\n }\n\n private func getDirEntries(dirTree: Data) throws -> [(String, InodeNumber)] {\n var children: [(String, InodeNumber)] = []\n var offset = 0\n while offset < dirTree.count {\n let length = MemoryLayout.size\n let dirEntry = dirTree.subdata(in: offset.. [(start: UInt32, end: UInt32)]? {\n let inode = try self.getInode(number: inode)\n let inodeBlock = Data(tupleToArray(inode.block))\n var offset = 0\n var extents: [(start: UInt32, end: UInt32)] = []\n\n let extentHeaderSize = MemoryLayout.size\n let extentIndexSize = MemoryLayout.size\n let extentLeafSize = MemoryLayout.size\n // read extent header\n let header = inodeBlock.subdata(in: offset.. Inode {\n if let inode = self.inodes[number] {\n return inode\n }\n\n let inode = try readInode(number)\n self.inodes[number] = inode\n return inode\n }\n\n func getGroupDescriptor(_ number: UInt32) throws -> GroupDescriptor {\n if let gd = self.groupDescriptors[number] {\n return gd\n }\n let gd = try readGroupDescriptor(number)\n self.groupDescriptors[number] = gd\n return gd\n }\n\n func children(of number: EXT4.InodeNumber) throws -> [(String, InodeNumber)] {\n try getDirTree(number)\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Platform.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// Source: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/config.go\n\nimport ContainerizationError\nimport Foundation\n\n/// Platform describes the platform which the image in the manifest runs on.\npublic struct Platform: Sendable, Equatable {\n public static var current: Self {\n var systemInfo = utsname()\n uname(&systemInfo)\n let arch = withUnsafePointer(to: &systemInfo.machine) {\n $0.withMemoryRebound(to: CChar.self, capacity: 1) {\n String(cString: $0)\n }\n }\n switch arch {\n case \"arm64\":\n return .init(arch: \"arm64\", os: \"linux\", variant: \"v8\")\n case \"x86_64\":\n return .init(arch: \"amd64\", os: \"linux\")\n default:\n fatalError(\"unsupported arch \\(arch)\")\n }\n }\n\n /// The computed description, for example, `linux/arm64/v8`.\n public var description: String {\n let architecture = architecture\n if let variant = variant {\n return \"\\(os)/\\(architecture)/\\(variant)\"\n }\n return \"\\(os)/\\(architecture)\"\n }\n\n /// The CPU architecture, for example, `amd64` or `ppc64`.\n public var architecture: String {\n switch _rawArch {\n case \"arm64\", \"arm\", \"aarch64\", \"armhf\", \"armel\":\n return \"arm64\"\n case \"x86_64\", \"x86-64\", \"amd64\":\n return \"amd64\"\n case \"386\", \"ppc64le\", \"i386\", \"s390x\", \"riscv64\":\n return _rawArch\n default:\n return _rawArch\n }\n }\n\n /// The operating system, for example, `linux` or `windows`.\n public var os: String {\n _rawOS\n }\n\n /// An optional field specifying the operating system version, for example on Windows `10.0.14393.1066`.\n public var osVersion: String?\n\n /// An optional field specifying an array of strings, each listing a required OS feature (for example on Windows `win32k`).\n public var osFeatures: [String]?\n\n /// An optional field specifying a variant of the CPU, for example `v7` to specify ARMv7 when architecture is `arm`.\n public var variant: String?\n\n /// The operation system of the image (eg. `linux`).\n private let _rawOS: String\n /// The CPU architecture (eg. `arm64`).\n private let _rawArch: String\n\n public init(arch: String, os: String, osVersion: String? = nil, osFeatures: [String]? = nil, variant: String? = nil) {\n self._rawArch = arch\n self._rawOS = os\n self.osVersion = osVersion\n self.osFeatures = osFeatures\n self.variant = variant\n }\n\n /// Initializes a new platform from a string.\n /// - Parameters:\n /// - platform: A `string` value representing the platform.\n /// ```swift\n /// // Create a new `ImagePlatform` from string.\n /// let platform = try Platform(from: \"linux/amd64\")\n /// ```\n /// ## Throws ##\n /// - Throws: `Error.missingOS` if input is empty\n /// - Throws: `Error.invalidOS` if os is not `linux`\n /// - Throws: `Error.missingArch` if only one `/` is present\n /// - Throws: `Error.invalidArch` if an unrecognized architecture is provided\n /// - Throws: `Error.invalidVariant` if a variant is provided, and it does not apply to the specified architecture\n public init(from platform: String) throws {\n let items = platform.split(separator: \"/\", maxSplits: 1)\n guard let osValue = items.first else {\n throw ContainerizationError(.invalidArgument, message: \"Missing OS in \\(platform)\")\n }\n switch osValue {\n case \"linux\":\n _rawOS = osValue.description\n case \"darwin\":\n _rawOS = osValue.description\n case \"windows\":\n _rawOS = osValue.description\n default:\n throw ContainerizationError(.invalidArgument, message: \"Unknown OS in \\(osValue)\")\n }\n guard items.count > 1 else {\n throw ContainerizationError(.invalidArgument, message: \"Missing architecture in \\(platform)\")\n }\n\n guard let archItems = items.last?.split(separator: \"/\", maxSplits: 1, omittingEmptySubsequences: false) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing architecture in \\(platform)\")\n }\n\n guard let archName = archItems.first else {\n throw ContainerizationError(.invalidArgument, message: \"Missing architecture in \\(platform)\")\n }\n\n switch archName {\n case \"arm\", \"armhf\", \"armel\":\n _rawArch = \"arm\"\n variant = \"v7\"\n case \"aarch64\", \"arm64\":\n variant = \"v8\"\n _rawArch = \"arm64\"\n case \"x86_64\", \"x86-64\", \"amd64\":\n _rawArch = \"amd64\"\n default:\n _rawArch = archName.description\n }\n\n if archItems.count == 2 {\n guard let archVariant = archItems.last else {\n throw ContainerizationError(.invalidArgument, message: \"Missing variant in \\(platform)\")\n }\n\n switch archName {\n case \"arm\":\n switch archVariant {\n case \"v5\", \"v6\", \"v7\", \"v8\":\n variant = archVariant.description\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n case \"armhf\":\n switch archVariant {\n case \"v7\":\n variant = \"v7\"\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n case \"armel\":\n switch archVariant {\n case \"v6\":\n variant = \"v6\"\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n case \"aarch64\", \"arm64\":\n switch archVariant {\n case \"v8\", \"8\":\n variant = \"v8\"\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n case \"x86_64\", \"x86-64\", \"amd64\":\n switch archVariant {\n case \"v1\":\n variant = nil\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n case \"i386\", \"386\", \"ppc64le\", \"riscv64\":\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n }\n }\n\n}\n\nextension Platform: Hashable {\n /**\n `~=` compares two platforms to check if **lhs** platform images are compatible with **rhs** platform\n This operator can be used to check if an image of **lhs** platform can run on **rhs**:\n - `true`: when **rhs**=`arm/v8`, **lhs** is any of `arm/v8`, `arm/v7`, `arm/v6` and `arm/v5`\n - `true`: when **rhs**=`arm/v7`, **lhs** is any of `arm/v7`, `arm/v6` and `arm/v5`\n - `true`: when **rhs**=`arm/v6`, **lhs** is any of `arm/v6` and `arm/v5`\n - `true`: when **rhs**=`amd64`, **lhs** is any of `amd64` and `386`\n - `true`: when **rhs**=**lhs**\n - `false`: otherwise\n - Parameters:\n - lhs: platform whose compatibility is being checked\n - rhs: platform against which compatibility is being checked\n - Returns: `true | false`\n */\n public static func ~= (lhs: Platform, rhs: Platform) -> Bool {\n if lhs.os == rhs.os {\n if lhs._rawArch == rhs._rawArch {\n switch rhs._rawArch {\n case \"arm\":\n guard let lVariant = lhs.variant else {\n return lhs == rhs\n }\n guard let rVariant = rhs.variant else {\n return lhs == rhs\n }\n switch rVariant {\n case \"v8\":\n switch lVariant {\n case \"v5\", \"v6\", \"v7\", \"v8\":\n return true\n default:\n return false\n }\n case \"v7\":\n switch lVariant {\n case \"v5\", \"v6\", \"v7\":\n return true\n default:\n return false\n }\n case \"v6\":\n switch lVariant {\n case \"v5\", \"v6\":\n return true\n default:\n return false\n }\n default:\n return lhs == rhs\n }\n default:\n return lhs == rhs\n }\n }\n if lhs._rawArch == \"386\" && rhs._rawArch == \"amd64\" {\n return true\n }\n }\n return false\n }\n\n /// `==` compares if **lhs** and **rhs** are the exact same platforms.\n public static func == (lhs: Platform, rhs: Platform) -> Bool {\n // NOTE:\n // If the platform struct was created by setting the fields directly and not using (from: String)\n // then, there is a possibility that for arm64 architecture, the variant may be set to nil\n // In that case, the variant should be assumed to v8\n if lhs.architecture == \"arm64\" && rhs.architecture == \"arm64\" {\n // The following checks effectively verify\n // that one operand has nil value and other has \"v8\"\n if lhs.variant == nil || rhs.variant == nil {\n if lhs.variant == \"v8\" || rhs.variant == \"v8\" {\n return true\n }\n }\n }\n\n let osEqual = lhs.os == rhs.os\n let archEqual = lhs.architecture == rhs.architecture\n let variantEqual = lhs.variant == rhs.variant\n\n return osEqual && archEqual && variantEqual\n }\n\n public func hash(into hasher: inout Swift.Hasher) {\n hasher.combine(description)\n }\n}\n\nextension Platform: Codable {\n\n enum CodingKeys: String, CodingKey {\n case os = \"os\"\n case architecture = \"architecture\"\n case variant = \"variant\"\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(os, forKey: .os)\n try container.encode(architecture, forKey: .architecture)\n try container.encodeIfPresent(variant, forKey: .variant)\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let architecture = try container.decodeIfPresent(String.self, forKey: .architecture)\n guard let architecture else {\n throw ContainerizationError(.invalidArgument, message: \"Missing architecture\")\n }\n let os = try container.decodeIfPresent(String.self, forKey: .os)\n guard let os else {\n throw ContainerizationError(.invalidArgument, message: \"Missing OS\")\n }\n let variant = try container.decodeIfPresent(String.self, forKey: .variant)\n self.init(arch: architecture, os: os, variant: variant)\n }\n}\n\npublic func createPlatformMatcher(for platform: Platform?) -> @Sendable (Platform) -> Bool {\n if let platform {\n return { other in\n platform == other\n }\n }\n return { _ in\n true\n }\n}\n\npublic func filterPlatforms(matcher: (Platform) -> Bool, _ descriptors: [Descriptor]) throws -> [Descriptor] {\n var outDescriptors: [Descriptor] = []\n for desc in descriptors {\n guard let p = desc.platform else {\n // pass along descriptor if the platform is not defined\n outDescriptors.append(desc)\n continue\n }\n if matcher(p) {\n outDescriptors.append(desc)\n }\n }\n return outDescriptors\n}\n"], ["/containerization/Sources/ContainerizationEXT4/Formatter+Unpack.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationArchive\nimport Foundation\nimport ContainerizationOS\nimport SystemPackage\nimport ContainerizationExtras\n\nprivate typealias Hardlinks = [FilePath: FilePath]\n\nextension EXT4.Formatter {\n /// Unpack the provided archive on to the ext4 filesystem.\n public func unpack(reader: ArchiveReader, progress: ProgressHandler? = nil) throws {\n var hardlinks: Hardlinks = [:]\n for (entry, data) in reader {\n try Task.checkCancellation()\n guard var pathEntry = entry.path else {\n continue\n }\n\n defer {\n // Count the number of entries\n if let progress {\n Task {\n await progress([\n ProgressEvent(event: \"add-items\", value: 1)\n ])\n }\n }\n }\n\n pathEntry = preProcessPath(s: pathEntry)\n let path = FilePath(pathEntry)\n\n if path.base.hasPrefix(\".wh.\") {\n if path.base == \".wh..wh..opq\" { // whiteout directory\n try self.unlink(path: path.dir, directoryWhiteout: true)\n continue\n }\n let startIndex = path.base.index(path.base.startIndex, offsetBy: \".wh.\".count)\n let filePath = String(path.base[startIndex...])\n let dir: FilePath = path.dir\n try self.unlink(path: dir.join(filePath))\n continue\n }\n\n if let hardlink = entry.hardlink {\n let hl = preProcessPath(s: hardlink)\n hardlinks[path] = FilePath(hl)\n continue\n }\n let ts = FileTimestamps(\n access: entry.contentAccessDate, modification: entry.modificationDate, creation: entry.creationDate)\n switch entry.fileType {\n case .directory:\n try self.create(\n path: path, mode: EXT4.Inode.Mode(.S_IFDIR, entry.permissions), ts: ts, uid: entry.owner,\n gid: entry.group,\n xattrs: entry.xattrs)\n case .regular:\n let inputStream = InputStream(data: data)\n inputStream.open()\n try self.create(\n path: path, mode: EXT4.Inode.Mode(.S_IFREG, entry.permissions), ts: ts, buf: inputStream,\n uid: entry.owner,\n gid: entry.group, xattrs: entry.xattrs)\n inputStream.close()\n\n // Count the size of files\n if let progress {\n Task {\n let size = Int64(data.count)\n await progress([\n ProgressEvent(event: \"add-size\", value: size)\n ])\n }\n }\n case .symbolicLink:\n var symlinkTarget: FilePath?\n if let target = entry.symlinkTarget {\n symlinkTarget = FilePath(target)\n }\n try self.create(\n path: path, link: symlinkTarget, mode: EXT4.Inode.Mode(.S_IFLNK, entry.permissions), ts: ts,\n uid: entry.owner,\n gid: entry.group, xattrs: entry.xattrs)\n default:\n continue\n }\n }\n guard hardlinks.acyclic else {\n throw UnpackError.circularLinks\n }\n for (path, _) in hardlinks {\n if let resolvedTarget = try hardlinks.resolve(path) {\n try self.link(link: path, target: resolvedTarget)\n }\n }\n }\n\n /// Unpack an archive at the source URL on to the ext4 filesystem.\n public func unpack(\n source: URL,\n format: ContainerizationArchive.Format = .paxRestricted,\n compression: ContainerizationArchive.Filter = .gzip,\n progress: ProgressHandler? = nil\n ) throws {\n let reader = try ArchiveReader(\n format: format,\n filter: compression,\n file: source\n )\n try self.unpack(reader: reader, progress: progress)\n }\n\n private func preProcessPath(s: String) -> String {\n var p = s\n if p.hasPrefix(\"./\") {\n p = String(p.dropFirst())\n }\n if !p.hasPrefix(\"/\") {\n p = \"/\" + p\n }\n return p\n }\n}\n\n/// Common errors for unpacking an archive onto an ext4 filesystem.\npublic enum UnpackError: Swift.Error, CustomStringConvertible, Sendable, Equatable {\n /// The name is invalid.\n case invalidName(_ name: String)\n /// A circular link is found.\n case circularLinks\n\n /// The description of the error.\n public var description: String {\n switch self {\n case .invalidName(let name):\n return \"'\\(name)' is an invalid name\"\n case .circularLinks:\n return \"circular links found\"\n }\n }\n}\n\nextension Hardlinks {\n fileprivate var acyclic: Bool {\n for (_, target) in self {\n var visited: Set = [target]\n var next = target\n while let item = self[next] {\n if visited.contains(item) {\n return false\n }\n next = item\n visited.insert(next)\n }\n }\n return true\n }\n\n fileprivate func resolve(_ key: FilePath) throws -> FilePath? {\n let target = self[key]\n guard let target else {\n return nil\n }\n var next = target\n let visited: Set = [next]\n while let item = self[next] {\n if visited.contains(item) {\n throw UnpackError.circularLinks\n }\n next = item\n }\n return next\n }\n}\n#endif\n"], ["/containerization/Sources/ContainerizationOS/Linux/Epoll.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(Linux)\n\n#if canImport(Musl)\nimport Musl\n#elseif canImport(Glibc)\nimport Glibc\n#else\n#error(\"Epoll not supported on this platform\")\n#endif\n\nimport Foundation\nimport Synchronization\n\n/// Register file descriptors to receive events via Linux's\n/// epoll syscall surface.\npublic final class Epoll: Sendable {\n public typealias Mask = Int32\n public typealias Handler = (@Sendable (Mask) -> Void)\n\n private let epollFD: Int32\n private let handlers = SafeMap()\n private let pipe = Pipe() // to wake up a waiting epoll_wait\n\n public init() throws {\n let efd = epoll_create1(EPOLL_CLOEXEC)\n guard efd > 0 else {\n throw POSIXError.fromErrno()\n }\n self.epollFD = efd\n try self.add(pipe.fileHandleForReading.fileDescriptor) { _ in }\n }\n\n public func add(\n _ fd: Int32,\n mask: Int32 = EPOLLIN | EPOLLOUT, // HUP is always added\n handler: @escaping Handler\n ) throws {\n guard fcntl(fd, F_SETFL, O_NONBLOCK) == 0 else {\n throw POSIXError.fromErrno()\n }\n\n let events = EPOLLET | UInt32(bitPattern: mask)\n\n var event = epoll_event()\n event.events = events\n event.data.fd = fd\n\n try withUnsafeMutablePointer(to: &event) { ptr in\n while true {\n if epoll_ctl(self.epollFD, EPOLL_CTL_ADD, fd, ptr) == -1 {\n if errno == EAGAIN || errno == EINTR {\n continue\n }\n throw POSIXError.fromErrno()\n }\n break\n }\n }\n\n self.handlers.set(fd, handler)\n }\n\n /// Run the main epoll loop.\n ///\n /// max events to return in a single wait\n /// timeout in ms.\n /// -1 means block forever.\n /// 0 means return immediately if no events.\n public func run(maxEvents: Int = 128, timeout: Int32 = -1) throws {\n var events: [epoll_event] = .init(\n repeating: epoll_event(),\n count: maxEvents\n )\n\n while true {\n let n = epoll_wait(self.epollFD, &events, Int32(events.count), timeout)\n guard n >= 0 else {\n if errno == EINTR || errno == EAGAIN {\n continue // go back to epoll_wait\n }\n throw POSIXError.fromErrno()\n }\n\n if n == 0 {\n return // if epoll wait times out, then n will be 0\n }\n\n for i in 0.. Bool {\n errno == ENOENT || errno == EBADF || errno == EPERM\n }\n\n /// Shutdown the epoll handler.\n public func shutdown() throws {\n // wakes up epoll_wait and triggers a shutdown\n try self.pipe.fileHandleForWriting.close()\n }\n\n private final class SafeMap: Sendable {\n let dict = Mutex<[Key: Value]>([:])\n\n func set(_ key: Key, _ value: Value) {\n dict.withLock { @Sendable in\n $0[key] = value\n }\n }\n\n func get(_ key: Key) -> Value? {\n dict.withLock { @Sendable in\n $0[key]\n }\n }\n\n func del(_ key: Key) {\n dict.withLock { @Sendable in\n _ = $0.removeValue(forKey: key)\n }\n }\n }\n}\n\nextension Epoll.Mask {\n public var isHangup: Bool {\n (self & (EPOLLHUP | EPOLLERR | EPOLLRDHUP)) != 0\n }\n\n public var readyToRead: Bool {\n (self & EPOLLIN) != 0\n }\n\n public var readyToWrite: Bool {\n (self & EPOLLOUT) != 0\n }\n}\n\n#endif // os(Linux)\n"], ["/containerization/Sources/Containerization/SandboxContext/SandboxContext.grpc.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n// DO NOT EDIT.\n// swift-format-ignore-file\n//\n// Generated by the protocol buffer compiler.\n// Source: SandboxContext.proto\n//\nimport GRPC\nimport NIO\nimport NIOConcurrencyHelpers\nimport SwiftProtobuf\n\n\n/// Context for interacting with a container's runtime environment.\n///\n/// Usage: instantiate `Com_Apple_Containerization_Sandbox_V3_SandboxContextClient`, then call methods of this protocol to make API calls.\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextClientProtocol: GRPCClient {\n var serviceName: String { get }\n var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? { get }\n\n func mount(\n _ request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func umount(\n _ request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func setenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func getenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func mkdir(\n _ request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func sysctl(\n _ request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func setTime(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func setupEmulator(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func createProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func deleteProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func startProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func killProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func waitProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func resizeProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func closeProcessStdin(\n _ request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func proxyVsock(\n _ request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func stopVsockProxy(\n _ request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func ipLinkSet(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func ipAddrAdd(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func ipRouteAddLink(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func ipRouteAddDefault(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func configureDns(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func configureHosts(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func sync(\n _ request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func kill(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextClientProtocol {\n public var serviceName: String {\n return \"com.apple.containerization.sandbox.v3.SandboxContext\"\n }\n\n /// Mount a filesystem.\n ///\n /// - Parameters:\n /// - request: Request to send to Mount.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func mount(\n _ request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMountInterceptors() ?? []\n )\n }\n\n /// Unmount a filesystem.\n ///\n /// - Parameters:\n /// - request: Request to send to Umount.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func umount(\n _ request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.umount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeUmountInterceptors() ?? []\n )\n }\n\n /// Set an environment variable on the init process.\n ///\n /// - Parameters:\n /// - request: Request to send to Setenv.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func setenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetenvInterceptors() ?? []\n )\n }\n\n /// Get an environment variable from the init process.\n ///\n /// - Parameters:\n /// - request: Request to send to Getenv.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func getenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.getenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeGetenvInterceptors() ?? []\n )\n }\n\n /// Create a new directory inside the sandbox.\n ///\n /// - Parameters:\n /// - request: Request to send to Mkdir.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func mkdir(\n _ request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mkdir.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMkdirInterceptors() ?? []\n )\n }\n\n /// Set sysctls in the context of the sandbox.\n ///\n /// - Parameters:\n /// - request: Request to send to Sysctl.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func sysctl(\n _ request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sysctl.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSysctlInterceptors() ?? []\n )\n }\n\n /// Set time in the guest.\n ///\n /// - Parameters:\n /// - request: Request to send to SetTime.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func setTime(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setTime.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetTimeInterceptors() ?? []\n )\n }\n\n /// Set up an emulator in the guest for a specific binary format.\n ///\n /// - Parameters:\n /// - request: Request to send to SetupEmulator.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func setupEmulator(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setupEmulator.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetupEmulatorInterceptors() ?? []\n )\n }\n\n /// Create a new process inside the container.\n ///\n /// - Parameters:\n /// - request: Request to send to CreateProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func createProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.createProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateProcessInterceptors() ?? []\n )\n }\n\n /// Delete an existing process inside the container.\n ///\n /// - Parameters:\n /// - request: Request to send to DeleteProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func deleteProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.deleteProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeDeleteProcessInterceptors() ?? []\n )\n }\n\n /// Start the provided process.\n ///\n /// - Parameters:\n /// - request: Request to send to StartProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func startProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.startProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStartProcessInterceptors() ?? []\n )\n }\n\n /// Send a signal to the provided process.\n ///\n /// - Parameters:\n /// - request: Request to send to KillProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func killProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.killProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillProcessInterceptors() ?? []\n )\n }\n\n /// Wait for a process to exit and return the exit code.\n ///\n /// - Parameters:\n /// - request: Request to send to WaitProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func waitProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.waitProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeWaitProcessInterceptors() ?? []\n )\n }\n\n /// Resize the tty of a given process. This will error if the process does\n /// not have a pty allocated.\n ///\n /// - Parameters:\n /// - request: Request to send to ResizeProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func resizeProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.resizeProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeResizeProcessInterceptors() ?? []\n )\n }\n\n /// Close IO for a given process.\n ///\n /// - Parameters:\n /// - request: Request to send to CloseProcessStdin.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func closeProcessStdin(\n _ request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.closeProcessStdin.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCloseProcessStdinInterceptors() ?? []\n )\n }\n\n /// Proxy a vsock port to a unix domain socket in the guest, or vice versa.\n ///\n /// - Parameters:\n /// - request: Request to send to ProxyVsock.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func proxyVsock(\n _ request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.proxyVsock.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeProxyVsockInterceptors() ?? []\n )\n }\n\n /// Stop a vsock proxy to a unix domain socket.\n ///\n /// - Parameters:\n /// - request: Request to send to StopVsockProxy.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func stopVsockProxy(\n _ request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.stopVsockProxy.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStopVsockProxyInterceptors() ?? []\n )\n }\n\n /// Set the link state of a network interface.\n ///\n /// - Parameters:\n /// - request: Request to send to IpLinkSet.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func ipLinkSet(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipLinkSet.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpLinkSetInterceptors() ?? []\n )\n }\n\n /// Add an IPv4 address to a network interface.\n ///\n /// - Parameters:\n /// - request: Request to send to IpAddrAdd.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func ipAddrAdd(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipAddrAdd.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpAddrAddInterceptors() ?? []\n )\n }\n\n /// Add an IP route for a network interface.\n ///\n /// - Parameters:\n /// - request: Request to send to IpRouteAddLink.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func ipRouteAddLink(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddLink.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddLinkInterceptors() ?? []\n )\n }\n\n /// Add an IP route for a network interface.\n ///\n /// - Parameters:\n /// - request: Request to send to IpRouteAddDefault.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func ipRouteAddDefault(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddDefault.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddDefaultInterceptors() ?? []\n )\n }\n\n /// Configure DNS resolver.\n ///\n /// - Parameters:\n /// - request: Request to send to ConfigureDns.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func configureDns(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureDns.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureDnsInterceptors() ?? []\n )\n }\n\n /// Configure /etc/hosts.\n ///\n /// - Parameters:\n /// - request: Request to send to ConfigureHosts.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func configureHosts(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureHosts.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureHostsInterceptors() ?? []\n )\n }\n\n /// Perform the sync syscall.\n ///\n /// - Parameters:\n /// - request: Request to send to Sync.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func sync(\n _ request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sync.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSyncInterceptors() ?? []\n )\n }\n\n /// Send a signal to a process via the PID.\n ///\n /// - Parameters:\n /// - request: Request to send to Kill.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func kill(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.kill.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillInterceptors() ?? []\n )\n }\n}\n\n@available(*, deprecated)\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextClient: @unchecked Sendable {}\n\n@available(*, deprecated, renamed: \"Com_Apple_Containerization_Sandbox_V3_SandboxContextNIOClient\")\npublic final class Com_Apple_Containerization_Sandbox_V3_SandboxContextClient: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientProtocol {\n private let lock = Lock()\n private var _defaultCallOptions: CallOptions\n private var _interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol?\n public let channel: GRPCChannel\n public var defaultCallOptions: CallOptions {\n get { self.lock.withLock { return self._defaultCallOptions } }\n set { self.lock.withLockVoid { self._defaultCallOptions = newValue } }\n }\n public var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? {\n get { self.lock.withLock { return self._interceptors } }\n set { self.lock.withLockVoid { self._interceptors = newValue } }\n }\n\n /// Creates a client for the com.apple.containerization.sandbox.v3.SandboxContext service.\n ///\n /// - Parameters:\n /// - channel: `GRPCChannel` to the service host.\n /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them.\n /// - interceptors: A factory providing interceptors for each RPC.\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self._defaultCallOptions = defaultCallOptions\n self._interceptors = interceptors\n }\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SandboxContextNIOClient: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientProtocol {\n public var channel: GRPCChannel\n public var defaultCallOptions: CallOptions\n public var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol?\n\n /// Creates a client for the com.apple.containerization.sandbox.v3.SandboxContext service.\n ///\n /// - Parameters:\n /// - channel: `GRPCChannel` to the service host.\n /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them.\n /// - interceptors: A factory providing interceptors for each RPC.\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self.defaultCallOptions = defaultCallOptions\n self.interceptors = interceptors\n }\n}\n\n/// Context for interacting with a container's runtime environment.\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClientProtocol: GRPCClient {\n static var serviceDescriptor: GRPCServiceDescriptor { get }\n var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? { get }\n\n func makeMountCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeUmountCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeSetenvCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeGetenvCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeMkdirCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeSysctlCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeSetTimeCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeSetupEmulatorCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeCreateProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeDeleteProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeStartProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeKillProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeWaitProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeResizeProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeCloseProcessStdinCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeProxyVsockCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeStopVsockProxyCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeIpLinkSetCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeIpAddrAddCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeIpRouteAddLinkCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeIpRouteAddDefaultCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeConfigureDnsCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeConfigureHostsCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeSyncCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeKillCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClientProtocol {\n public static var serviceDescriptor: GRPCServiceDescriptor {\n return Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.serviceDescriptor\n }\n\n public var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? {\n return nil\n }\n\n public func makeMountCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMountInterceptors() ?? []\n )\n }\n\n public func makeUmountCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.umount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeUmountInterceptors() ?? []\n )\n }\n\n public func makeSetenvCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetenvInterceptors() ?? []\n )\n }\n\n public func makeGetenvCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.getenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeGetenvInterceptors() ?? []\n )\n }\n\n public func makeMkdirCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mkdir.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMkdirInterceptors() ?? []\n )\n }\n\n public func makeSysctlCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sysctl.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSysctlInterceptors() ?? []\n )\n }\n\n public func makeSetTimeCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setTime.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetTimeInterceptors() ?? []\n )\n }\n\n public func makeSetupEmulatorCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setupEmulator.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetupEmulatorInterceptors() ?? []\n )\n }\n\n public func makeCreateProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.createProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateProcessInterceptors() ?? []\n )\n }\n\n public func makeDeleteProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.deleteProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeDeleteProcessInterceptors() ?? []\n )\n }\n\n public func makeStartProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.startProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStartProcessInterceptors() ?? []\n )\n }\n\n public func makeKillProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.killProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillProcessInterceptors() ?? []\n )\n }\n\n public func makeWaitProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.waitProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeWaitProcessInterceptors() ?? []\n )\n }\n\n public func makeResizeProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.resizeProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeResizeProcessInterceptors() ?? []\n )\n }\n\n public func makeCloseProcessStdinCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.closeProcessStdin.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCloseProcessStdinInterceptors() ?? []\n )\n }\n\n public func makeProxyVsockCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.proxyVsock.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeProxyVsockInterceptors() ?? []\n )\n }\n\n public func makeStopVsockProxyCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.stopVsockProxy.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStopVsockProxyInterceptors() ?? []\n )\n }\n\n public func makeIpLinkSetCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipLinkSet.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpLinkSetInterceptors() ?? []\n )\n }\n\n public func makeIpAddrAddCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipAddrAdd.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpAddrAddInterceptors() ?? []\n )\n }\n\n public func makeIpRouteAddLinkCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddLink.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddLinkInterceptors() ?? []\n )\n }\n\n public func makeIpRouteAddDefaultCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddDefault.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddDefaultInterceptors() ?? []\n )\n }\n\n public func makeConfigureDnsCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureDns.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureDnsInterceptors() ?? []\n )\n }\n\n public func makeConfigureHostsCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureHosts.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureHostsInterceptors() ?? []\n )\n }\n\n public func makeSyncCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sync.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSyncInterceptors() ?? []\n )\n }\n\n public func makeKillCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.kill.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillInterceptors() ?? []\n )\n }\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClientProtocol {\n public func mount(\n _ request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_MountResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMountInterceptors() ?? []\n )\n }\n\n public func umount(\n _ request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_UmountResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.umount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeUmountInterceptors() ?? []\n )\n }\n\n public func setenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetenvResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetenvInterceptors() ?? []\n )\n }\n\n public func getenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_GetenvResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.getenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeGetenvInterceptors() ?? []\n )\n }\n\n public func mkdir(\n _ request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_MkdirResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mkdir.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMkdirInterceptors() ?? []\n )\n }\n\n public func sysctl(\n _ request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SysctlResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sysctl.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSysctlInterceptors() ?? []\n )\n }\n\n public func setTime(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetTimeResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setTime.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetTimeInterceptors() ?? []\n )\n }\n\n public func setupEmulator(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setupEmulator.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetupEmulatorInterceptors() ?? []\n )\n }\n\n public func createProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.createProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateProcessInterceptors() ?? []\n )\n }\n\n public func deleteProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.deleteProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeDeleteProcessInterceptors() ?? []\n )\n }\n\n public func startProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StartProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.startProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStartProcessInterceptors() ?? []\n )\n }\n\n public func killProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.killProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillProcessInterceptors() ?? []\n )\n }\n\n public func waitProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.waitProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeWaitProcessInterceptors() ?? []\n )\n }\n\n public func resizeProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.resizeProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeResizeProcessInterceptors() ?? []\n )\n }\n\n public func closeProcessStdin(\n _ request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.closeProcessStdin.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCloseProcessStdinInterceptors() ?? []\n )\n }\n\n public func proxyVsock(\n _ request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.proxyVsock.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeProxyVsockInterceptors() ?? []\n )\n }\n\n public func stopVsockProxy(\n _ request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.stopVsockProxy.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStopVsockProxyInterceptors() ?? []\n )\n }\n\n public func ipLinkSet(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipLinkSet.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpLinkSetInterceptors() ?? []\n )\n }\n\n public func ipAddrAdd(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipAddrAdd.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpAddrAddInterceptors() ?? []\n )\n }\n\n public func ipRouteAddLink(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddLink.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddLinkInterceptors() ?? []\n )\n }\n\n public func ipRouteAddDefault(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddDefault.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddDefaultInterceptors() ?? []\n )\n }\n\n public func configureDns(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureDns.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureDnsInterceptors() ?? []\n )\n }\n\n public func configureHosts(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureHosts.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureHostsInterceptors() ?? []\n )\n }\n\n public func sync(\n _ request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SyncResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sync.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSyncInterceptors() ?? []\n )\n }\n\n public func kill(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.kill.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillInterceptors() ?? []\n )\n }\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic struct Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClient: Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClientProtocol {\n public var channel: GRPCChannel\n public var defaultCallOptions: CallOptions\n public var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol?\n\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self.defaultCallOptions = defaultCallOptions\n self.interceptors = interceptors\n }\n}\n\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol: Sendable {\n\n /// - Returns: Interceptors to use when invoking 'mount'.\n func makeMountInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'umount'.\n func makeUmountInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'setenv'.\n func makeSetenvInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'getenv'.\n func makeGetenvInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'mkdir'.\n func makeMkdirInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'sysctl'.\n func makeSysctlInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'setTime'.\n func makeSetTimeInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'setupEmulator'.\n func makeSetupEmulatorInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'createProcess'.\n func makeCreateProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'deleteProcess'.\n func makeDeleteProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'startProcess'.\n func makeStartProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'killProcess'.\n func makeKillProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'waitProcess'.\n func makeWaitProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'resizeProcess'.\n func makeResizeProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'closeProcessStdin'.\n func makeCloseProcessStdinInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'proxyVsock'.\n func makeProxyVsockInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'stopVsockProxy'.\n func makeStopVsockProxyInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'ipLinkSet'.\n func makeIpLinkSetInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'ipAddrAdd'.\n func makeIpAddrAddInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'ipRouteAddLink'.\n func makeIpRouteAddLinkInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'ipRouteAddDefault'.\n func makeIpRouteAddDefaultInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'configureDns'.\n func makeConfigureDnsInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'configureHosts'.\n func makeConfigureHostsInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'sync'.\n func makeSyncInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'kill'.\n func makeKillInterceptors() -> [ClientInterceptor]\n}\n\npublic enum Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata {\n public static let serviceDescriptor = GRPCServiceDescriptor(\n name: \"SandboxContext\",\n fullName: \"com.apple.containerization.sandbox.v3.SandboxContext\",\n methods: [\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mount,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.umount,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setenv,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.getenv,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mkdir,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sysctl,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setTime,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setupEmulator,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.createProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.deleteProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.startProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.killProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.waitProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.resizeProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.closeProcessStdin,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.proxyVsock,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.stopVsockProxy,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipLinkSet,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipAddrAdd,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddLink,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddDefault,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureDns,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureHosts,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sync,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.kill,\n ]\n )\n\n public enum Methods {\n public static let mount = GRPCMethodDescriptor(\n name: \"Mount\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Mount\",\n type: GRPCCallType.unary\n )\n\n public static let umount = GRPCMethodDescriptor(\n name: \"Umount\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Umount\",\n type: GRPCCallType.unary\n )\n\n public static let setenv = GRPCMethodDescriptor(\n name: \"Setenv\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Setenv\",\n type: GRPCCallType.unary\n )\n\n public static let getenv = GRPCMethodDescriptor(\n name: \"Getenv\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Getenv\",\n type: GRPCCallType.unary\n )\n\n public static let mkdir = GRPCMethodDescriptor(\n name: \"Mkdir\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Mkdir\",\n type: GRPCCallType.unary\n )\n\n public static let sysctl = GRPCMethodDescriptor(\n name: \"Sysctl\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Sysctl\",\n type: GRPCCallType.unary\n )\n\n public static let setTime = GRPCMethodDescriptor(\n name: \"SetTime\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/SetTime\",\n type: GRPCCallType.unary\n )\n\n public static let setupEmulator = GRPCMethodDescriptor(\n name: \"SetupEmulator\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/SetupEmulator\",\n type: GRPCCallType.unary\n )\n\n public static let createProcess = GRPCMethodDescriptor(\n name: \"CreateProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/CreateProcess\",\n type: GRPCCallType.unary\n )\n\n public static let deleteProcess = GRPCMethodDescriptor(\n name: \"DeleteProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/DeleteProcess\",\n type: GRPCCallType.unary\n )\n\n public static let startProcess = GRPCMethodDescriptor(\n name: \"StartProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/StartProcess\",\n type: GRPCCallType.unary\n )\n\n public static let killProcess = GRPCMethodDescriptor(\n name: \"KillProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/KillProcess\",\n type: GRPCCallType.unary\n )\n\n public static let waitProcess = GRPCMethodDescriptor(\n name: \"WaitProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/WaitProcess\",\n type: GRPCCallType.unary\n )\n\n public static let resizeProcess = GRPCMethodDescriptor(\n name: \"ResizeProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ResizeProcess\",\n type: GRPCCallType.unary\n )\n\n public static let closeProcessStdin = GRPCMethodDescriptor(\n name: \"CloseProcessStdin\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/CloseProcessStdin\",\n type: GRPCCallType.unary\n )\n\n public static let proxyVsock = GRPCMethodDescriptor(\n name: \"ProxyVsock\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ProxyVsock\",\n type: GRPCCallType.unary\n )\n\n public static let stopVsockProxy = GRPCMethodDescriptor(\n name: \"StopVsockProxy\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/StopVsockProxy\",\n type: GRPCCallType.unary\n )\n\n public static let ipLinkSet = GRPCMethodDescriptor(\n name: \"IpLinkSet\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpLinkSet\",\n type: GRPCCallType.unary\n )\n\n public static let ipAddrAdd = GRPCMethodDescriptor(\n name: \"IpAddrAdd\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpAddrAdd\",\n type: GRPCCallType.unary\n )\n\n public static let ipRouteAddLink = GRPCMethodDescriptor(\n name: \"IpRouteAddLink\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpRouteAddLink\",\n type: GRPCCallType.unary\n )\n\n public static let ipRouteAddDefault = GRPCMethodDescriptor(\n name: \"IpRouteAddDefault\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpRouteAddDefault\",\n type: GRPCCallType.unary\n )\n\n public static let configureDns = GRPCMethodDescriptor(\n name: \"ConfigureDns\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ConfigureDns\",\n type: GRPCCallType.unary\n )\n\n public static let configureHosts = GRPCMethodDescriptor(\n name: \"ConfigureHosts\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ConfigureHosts\",\n type: GRPCCallType.unary\n )\n\n public static let sync = GRPCMethodDescriptor(\n name: \"Sync\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Sync\",\n type: GRPCCallType.unary\n )\n\n public static let kill = GRPCMethodDescriptor(\n name: \"Kill\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Kill\",\n type: GRPCCallType.unary\n )\n }\n}\n\n/// Context for interacting with a container's runtime environment.\n///\n/// To build a server, implement a class that conforms to this protocol.\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextProvider: CallHandlerProvider {\n var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextServerInterceptorFactoryProtocol? { get }\n\n /// Mount a filesystem.\n func mount(request: Com_Apple_Containerization_Sandbox_V3_MountRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Unmount a filesystem.\n func umount(request: Com_Apple_Containerization_Sandbox_V3_UmountRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Set an environment variable on the init process.\n func setenv(request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Get an environment variable from the init process.\n func getenv(request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Create a new directory inside the sandbox.\n func mkdir(request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Set sysctls in the context of the sandbox.\n func sysctl(request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Set time in the guest.\n func setTime(request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Set up an emulator in the guest for a specific binary format.\n func setupEmulator(request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Create a new process inside the container.\n func createProcess(request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Delete an existing process inside the container.\n func deleteProcess(request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Start the provided process.\n func startProcess(request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Send a signal to the provided process.\n func killProcess(request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Wait for a process to exit and return the exit code.\n func waitProcess(request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Resize the tty of a given process. This will error if the process does\n /// not have a pty allocated.\n func resizeProcess(request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Close IO for a given process.\n func closeProcessStdin(request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Proxy a vsock port to a unix domain socket in the guest, or vice versa.\n func proxyVsock(request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Stop a vsock proxy to a unix domain socket.\n func stopVsockProxy(request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Set the link state of a network interface.\n func ipLinkSet(request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Add an IPv4 address to a network interface.\n func ipAddrAdd(request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Add an IP route for a network interface.\n func ipRouteAddLink(request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Add an IP route for a network interface.\n func ipRouteAddDefault(request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Configure DNS resolver.\n func configureDns(request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Configure /etc/hosts.\n func configureHosts(request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Perform the sync syscall.\n func sync(request: Com_Apple_Containerization_Sandbox_V3_SyncRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Send a signal to a process via the PID.\n func kill(request: Com_Apple_Containerization_Sandbox_V3_KillRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextProvider {\n public var serviceName: Substring {\n return Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.serviceDescriptor.fullName[...]\n }\n\n /// Determines, calls and returns the appropriate request handler, depending on the request's method.\n /// Returns nil for methods not handled by this service.\n public func handle(\n method name: Substring,\n context: CallHandlerContext\n ) -> GRPCServerHandlerProtocol? {\n switch name {\n case \"Mount\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeMountInterceptors() ?? [],\n userFunction: self.mount(request:context:)\n )\n\n case \"Umount\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeUmountInterceptors() ?? [],\n userFunction: self.umount(request:context:)\n )\n\n case \"Setenv\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetenvInterceptors() ?? [],\n userFunction: self.setenv(request:context:)\n )\n\n case \"Getenv\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeGetenvInterceptors() ?? [],\n userFunction: self.getenv(request:context:)\n )\n\n case \"Mkdir\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeMkdirInterceptors() ?? [],\n userFunction: self.mkdir(request:context:)\n )\n\n case \"Sysctl\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSysctlInterceptors() ?? [],\n userFunction: self.sysctl(request:context:)\n )\n\n case \"SetTime\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetTimeInterceptors() ?? [],\n userFunction: self.setTime(request:context:)\n )\n\n case \"SetupEmulator\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetupEmulatorInterceptors() ?? [],\n userFunction: self.setupEmulator(request:context:)\n )\n\n case \"CreateProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCreateProcessInterceptors() ?? [],\n userFunction: self.createProcess(request:context:)\n )\n\n case \"DeleteProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeDeleteProcessInterceptors() ?? [],\n userFunction: self.deleteProcess(request:context:)\n )\n\n case \"StartProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeStartProcessInterceptors() ?? [],\n userFunction: self.startProcess(request:context:)\n )\n\n case \"KillProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeKillProcessInterceptors() ?? [],\n userFunction: self.killProcess(request:context:)\n )\n\n case \"WaitProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeWaitProcessInterceptors() ?? [],\n userFunction: self.waitProcess(request:context:)\n )\n\n case \"ResizeProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeResizeProcessInterceptors() ?? [],\n userFunction: self.resizeProcess(request:context:)\n )\n\n case \"CloseProcessStdin\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCloseProcessStdinInterceptors() ?? [],\n userFunction: self.closeProcessStdin(request:context:)\n )\n\n case \"ProxyVsock\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeProxyVsockInterceptors() ?? [],\n userFunction: self.proxyVsock(request:context:)\n )\n\n case \"StopVsockProxy\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeStopVsockProxyInterceptors() ?? [],\n userFunction: self.stopVsockProxy(request:context:)\n )\n\n case \"IpLinkSet\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpLinkSetInterceptors() ?? [],\n userFunction: self.ipLinkSet(request:context:)\n )\n\n case \"IpAddrAdd\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpAddrAddInterceptors() ?? [],\n userFunction: self.ipAddrAdd(request:context:)\n )\n\n case \"IpRouteAddLink\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpRouteAddLinkInterceptors() ?? [],\n userFunction: self.ipRouteAddLink(request:context:)\n )\n\n case \"IpRouteAddDefault\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpRouteAddDefaultInterceptors() ?? [],\n userFunction: self.ipRouteAddDefault(request:context:)\n )\n\n case \"ConfigureDns\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeConfigureDnsInterceptors() ?? [],\n userFunction: self.configureDns(request:context:)\n )\n\n case \"ConfigureHosts\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeConfigureHostsInterceptors() ?? [],\n userFunction: self.configureHosts(request:context:)\n )\n\n case \"Sync\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSyncInterceptors() ?? [],\n userFunction: self.sync(request:context:)\n )\n\n case \"Kill\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeKillInterceptors() ?? [],\n userFunction: self.kill(request:context:)\n )\n\n default:\n return nil\n }\n }\n}\n\n/// Context for interacting with a container's runtime environment.\n///\n/// To implement a server, implement an object which conforms to this protocol.\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncProvider: CallHandlerProvider, Sendable {\n static var serviceDescriptor: GRPCServiceDescriptor { get }\n var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextServerInterceptorFactoryProtocol? { get }\n\n /// Mount a filesystem.\n func mount(\n request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_MountResponse\n\n /// Unmount a filesystem.\n func umount(\n request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_UmountResponse\n\n /// Set an environment variable on the init process.\n func setenv(\n request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetenvResponse\n\n /// Get an environment variable from the init process.\n func getenv(\n request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_GetenvResponse\n\n /// Create a new directory inside the sandbox.\n func mkdir(\n request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_MkdirResponse\n\n /// Set sysctls in the context of the sandbox.\n func sysctl(\n request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SysctlResponse\n\n /// Set time in the guest.\n func setTime(\n request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetTimeResponse\n\n /// Set up an emulator in the guest for a specific binary format.\n func setupEmulator(\n request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse\n\n /// Create a new process inside the container.\n func createProcess(\n request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse\n\n /// Delete an existing process inside the container.\n func deleteProcess(\n request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse\n\n /// Start the provided process.\n func startProcess(\n request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StartProcessResponse\n\n /// Send a signal to the provided process.\n func killProcess(\n request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillProcessResponse\n\n /// Wait for a process to exit and return the exit code.\n func waitProcess(\n request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse\n\n /// Resize the tty of a given process. This will error if the process does\n /// not have a pty allocated.\n func resizeProcess(\n request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse\n\n /// Close IO for a given process.\n func closeProcessStdin(\n request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse\n\n /// Proxy a vsock port to a unix domain socket in the guest, or vice versa.\n func proxyVsock(\n request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse\n\n /// Stop a vsock proxy to a unix domain socket.\n func stopVsockProxy(\n request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse\n\n /// Set the link state of a network interface.\n func ipLinkSet(\n request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse\n\n /// Add an IPv4 address to a network interface.\n func ipAddrAdd(\n request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse\n\n /// Add an IP route for a network interface.\n func ipRouteAddLink(\n request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse\n\n /// Add an IP route for a network interface.\n func ipRouteAddDefault(\n request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse\n\n /// Configure DNS resolver.\n func configureDns(\n request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse\n\n /// Configure /etc/hosts.\n func configureHosts(\n request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse\n\n /// Perform the sync syscall.\n func sync(\n request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SyncResponse\n\n /// Send a signal to a process via the PID.\n func kill(\n request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillResponse\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncProvider {\n public static var serviceDescriptor: GRPCServiceDescriptor {\n return Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.serviceDescriptor\n }\n\n public var serviceName: Substring {\n return Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.serviceDescriptor.fullName[...]\n }\n\n public var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextServerInterceptorFactoryProtocol? {\n return nil\n }\n\n public func handle(\n method name: Substring,\n context: CallHandlerContext\n ) -> GRPCServerHandlerProtocol? {\n switch name {\n case \"Mount\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeMountInterceptors() ?? [],\n wrapping: { try await self.mount(request: $0, context: $1) }\n )\n\n case \"Umount\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeUmountInterceptors() ?? [],\n wrapping: { try await self.umount(request: $0, context: $1) }\n )\n\n case \"Setenv\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetenvInterceptors() ?? [],\n wrapping: { try await self.setenv(request: $0, context: $1) }\n )\n\n case \"Getenv\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeGetenvInterceptors() ?? [],\n wrapping: { try await self.getenv(request: $0, context: $1) }\n )\n\n case \"Mkdir\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeMkdirInterceptors() ?? [],\n wrapping: { try await self.mkdir(request: $0, context: $1) }\n )\n\n case \"Sysctl\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSysctlInterceptors() ?? [],\n wrapping: { try await self.sysctl(request: $0, context: $1) }\n )\n\n case \"SetTime\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetTimeInterceptors() ?? [],\n wrapping: { try await self.setTime(request: $0, context: $1) }\n )\n\n case \"SetupEmulator\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetupEmulatorInterceptors() ?? [],\n wrapping: { try await self.setupEmulator(request: $0, context: $1) }\n )\n\n case \"CreateProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCreateProcessInterceptors() ?? [],\n wrapping: { try await self.createProcess(request: $0, context: $1) }\n )\n\n case \"DeleteProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeDeleteProcessInterceptors() ?? [],\n wrapping: { try await self.deleteProcess(request: $0, context: $1) }\n )\n\n case \"StartProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeStartProcessInterceptors() ?? [],\n wrapping: { try await self.startProcess(request: $0, context: $1) }\n )\n\n case \"KillProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeKillProcessInterceptors() ?? [],\n wrapping: { try await self.killProcess(request: $0, context: $1) }\n )\n\n case \"WaitProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeWaitProcessInterceptors() ?? [],\n wrapping: { try await self.waitProcess(request: $0, context: $1) }\n )\n\n case \"ResizeProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeResizeProcessInterceptors() ?? [],\n wrapping: { try await self.resizeProcess(request: $0, context: $1) }\n )\n\n case \"CloseProcessStdin\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCloseProcessStdinInterceptors() ?? [],\n wrapping: { try await self.closeProcessStdin(request: $0, context: $1) }\n )\n\n case \"ProxyVsock\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeProxyVsockInterceptors() ?? [],\n wrapping: { try await self.proxyVsock(request: $0, context: $1) }\n )\n\n case \"StopVsockProxy\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeStopVsockProxyInterceptors() ?? [],\n wrapping: { try await self.stopVsockProxy(request: $0, context: $1) }\n )\n\n case \"IpLinkSet\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpLinkSetInterceptors() ?? [],\n wrapping: { try await self.ipLinkSet(request: $0, context: $1) }\n )\n\n case \"IpAddrAdd\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpAddrAddInterceptors() ?? [],\n wrapping: { try await self.ipAddrAdd(request: $0, context: $1) }\n )\n\n case \"IpRouteAddLink\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpRouteAddLinkInterceptors() ?? [],\n wrapping: { try await self.ipRouteAddLink(request: $0, context: $1) }\n )\n\n case \"IpRouteAddDefault\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpRouteAddDefaultInterceptors() ?? [],\n wrapping: { try await self.ipRouteAddDefault(request: $0, context: $1) }\n )\n\n case \"ConfigureDns\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeConfigureDnsInterceptors() ?? [],\n wrapping: { try await self.configureDns(request: $0, context: $1) }\n )\n\n case \"ConfigureHosts\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeConfigureHostsInterceptors() ?? [],\n wrapping: { try await self.configureHosts(request: $0, context: $1) }\n )\n\n case \"Sync\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSyncInterceptors() ?? [],\n wrapping: { try await self.sync(request: $0, context: $1) }\n )\n\n case \"Kill\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeKillInterceptors() ?? [],\n wrapping: { try await self.kill(request: $0, context: $1) }\n )\n\n default:\n return nil\n }\n }\n}\n\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextServerInterceptorFactoryProtocol: Sendable {\n\n /// - Returns: Interceptors to use when handling 'mount'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeMountInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'umount'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeUmountInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'setenv'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeSetenvInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'getenv'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeGetenvInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'mkdir'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeMkdirInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'sysctl'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeSysctlInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'setTime'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeSetTimeInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'setupEmulator'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeSetupEmulatorInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'createProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeCreateProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'deleteProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeDeleteProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'startProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeStartProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'killProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeKillProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'waitProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeWaitProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'resizeProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeResizeProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'closeProcessStdin'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeCloseProcessStdinInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'proxyVsock'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeProxyVsockInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'stopVsockProxy'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeStopVsockProxyInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'ipLinkSet'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeIpLinkSetInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'ipAddrAdd'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeIpAddrAddInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'ipRouteAddLink'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeIpRouteAddLinkInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'ipRouteAddDefault'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeIpRouteAddDefaultInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'configureDns'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeConfigureDnsInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'configureHosts'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeConfigureHostsInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'sync'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeSyncInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'kill'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeKillInterceptors() -> [ServerInterceptor]\n}\n\npublic enum Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata {\n public static let serviceDescriptor = GRPCServiceDescriptor(\n name: \"SandboxContext\",\n fullName: \"com.apple.containerization.sandbox.v3.SandboxContext\",\n methods: [\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.mount,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.umount,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.setenv,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.getenv,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.mkdir,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.sysctl,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.setTime,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.setupEmulator,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.createProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.deleteProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.startProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.killProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.waitProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.resizeProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.closeProcessStdin,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.proxyVsock,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.stopVsockProxy,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.ipLinkSet,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.ipAddrAdd,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.ipRouteAddLink,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.ipRouteAddDefault,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.configureDns,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.configureHosts,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.sync,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.kill,\n ]\n )\n\n public enum Methods {\n public static let mount = GRPCMethodDescriptor(\n name: \"Mount\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Mount\",\n type: GRPCCallType.unary\n )\n\n public static let umount = GRPCMethodDescriptor(\n name: \"Umount\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Umount\",\n type: GRPCCallType.unary\n )\n\n public static let setenv = GRPCMethodDescriptor(\n name: \"Setenv\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Setenv\",\n type: GRPCCallType.unary\n )\n\n public static let getenv = GRPCMethodDescriptor(\n name: \"Getenv\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Getenv\",\n type: GRPCCallType.unary\n )\n\n public static let mkdir = GRPCMethodDescriptor(\n name: \"Mkdir\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Mkdir\",\n type: GRPCCallType.unary\n )\n\n public static let sysctl = GRPCMethodDescriptor(\n name: \"Sysctl\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Sysctl\",\n type: GRPCCallType.unary\n )\n\n public static let setTime = GRPCMethodDescriptor(\n name: \"SetTime\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/SetTime\",\n type: GRPCCallType.unary\n )\n\n public static let setupEmulator = GRPCMethodDescriptor(\n name: \"SetupEmulator\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/SetupEmulator\",\n type: GRPCCallType.unary\n )\n\n public static let createProcess = GRPCMethodDescriptor(\n name: \"CreateProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/CreateProcess\",\n type: GRPCCallType.unary\n )\n\n public static let deleteProcess = GRPCMethodDescriptor(\n name: \"DeleteProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/DeleteProcess\",\n type: GRPCCallType.unary\n )\n\n public static let startProcess = GRPCMethodDescriptor(\n name: \"StartProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/StartProcess\",\n type: GRPCCallType.unary\n )\n\n public static let killProcess = GRPCMethodDescriptor(\n name: \"KillProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/KillProcess\",\n type: GRPCCallType.unary\n )\n\n public static let waitProcess = GRPCMethodDescriptor(\n name: \"WaitProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/WaitProcess\",\n type: GRPCCallType.unary\n )\n\n public static let resizeProcess = GRPCMethodDescriptor(\n name: \"ResizeProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ResizeProcess\",\n type: GRPCCallType.unary\n )\n\n public static let closeProcessStdin = GRPCMethodDescriptor(\n name: \"CloseProcessStdin\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/CloseProcessStdin\",\n type: GRPCCallType.unary\n )\n\n public static let proxyVsock = GRPCMethodDescriptor(\n name: \"ProxyVsock\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ProxyVsock\",\n type: GRPCCallType.unary\n )\n\n public static let stopVsockProxy = GRPCMethodDescriptor(\n name: \"StopVsockProxy\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/StopVsockProxy\",\n type: GRPCCallType.unary\n )\n\n public static let ipLinkSet = GRPCMethodDescriptor(\n name: \"IpLinkSet\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpLinkSet\",\n type: GRPCCallType.unary\n )\n\n public static let ipAddrAdd = GRPCMethodDescriptor(\n name: \"IpAddrAdd\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpAddrAdd\",\n type: GRPCCallType.unary\n )\n\n public static let ipRouteAddLink = GRPCMethodDescriptor(\n name: \"IpRouteAddLink\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpRouteAddLink\",\n type: GRPCCallType.unary\n )\n\n public static let ipRouteAddDefault = GRPCMethodDescriptor(\n name: \"IpRouteAddDefault\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpRouteAddDefault\",\n type: GRPCCallType.unary\n )\n\n public static let configureDns = GRPCMethodDescriptor(\n name: \"ConfigureDns\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ConfigureDns\",\n type: GRPCCallType.unary\n )\n\n public static let configureHosts = GRPCMethodDescriptor(\n name: \"ConfigureHosts\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ConfigureHosts\",\n type: GRPCCallType.unary\n )\n\n public static let sync = GRPCMethodDescriptor(\n name: \"Sync\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Sync\",\n type: GRPCCallType.unary\n )\n\n public static let kill = GRPCMethodDescriptor(\n name: \"Kill\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Kill\",\n type: GRPCCallType.unary\n )\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/Application.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport NIOCore\nimport NIOPosix\n\n#if os(Linux)\nimport Musl\nimport LCShim\n#endif\n\n@main\nstruct Application {\n private static let foregroundEnvVar = \"FOREGROUND\"\n private static let vsockPort = 1024\n private static let standardErrorLock = NSLock()\n\n private static func runInForeground(_ log: Logger) throws {\n log.info(\"running vminitd under pid1\")\n\n var command = Command(\"/sbin/vminitd\")\n command.attrs = .init(setsid: true)\n command.stdin = .standardInput\n command.stdout = .standardOutput\n command.stderr = .standardError\n command.environment = [\"\\(foregroundEnvVar)=1\"]\n\n try command.start()\n _ = try command.wait()\n }\n\n private static func adjustLimits() throws {\n var limits = rlimit()\n guard getrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n limits.rlim_cur = 65536\n limits.rlim_max = 65536\n guard setrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n }\n\n @Sendable\n private static func standardError(label: String) -> StreamLogHandler {\n standardErrorLock.withLock {\n StreamLogHandler.standardError(label: label)\n }\n }\n\n static func main() async throws {\n LoggingSystem.bootstrap(standardError)\n var log = Logger(label: \"vminitd\")\n\n try adjustLimits()\n\n // when running under debug mode, launch vminitd as a sub process of pid1\n // so that we get a chance to collect better logs and errors before pid1 exists\n // and the kernel panics.\n #if DEBUG\n let environment = ProcessInfo.processInfo.environment\n let foreground = environment[Self.foregroundEnvVar]\n log.info(\"checking for shim var \\(foregroundEnvVar)=\\(String(describing: foreground))\")\n\n if foreground == nil {\n try runInForeground(log)\n exit(0)\n }\n\n // since we are not running as pid1 in this mode we must set ourselves\n // as a subpreaper so that all child processes are reaped by us and not\n // passed onto our parent.\n CZ_set_sub_reaper()\n #endif\n\n signal(SIGPIPE, SIG_IGN)\n\n // Because the sysctl rpc wouldn't make sense if this didn't always exist, we\n // ALWAYS mount /proc.\n guard Musl.mount(\"proc\", \"/proc\", \"proc\", 0, \"\") == 0 else {\n log.error(\"failed to mount /proc\")\n exit(1)\n }\n\n try Binfmt.mount()\n\n log.logLevel = .debug\n\n log.info(\"vminitd booting...\")\n let eg = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)\n let server = Initd(log: log, group: eg)\n\n do {\n log.info(\"serve vminitd api\")\n try await server.serve(port: vsockPort)\n log.info(\"vminitd api returned...\")\n } catch {\n log.error(\"vminitd boot error \\(error)\")\n exit(1)\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/Reader.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CArchive\nimport Foundation\n\n/// A class responsible for reading entries from an archive file.\npublic final class ArchiveReader {\n /// A pointer to the underlying `archive` C structure.\n var underlying: OpaquePointer?\n /// The file handle associated with the archive file being read.\n let fileHandle: FileHandle?\n\n /// Initializes an `ArchiveReader` to read from a specified file URL with an explicit `Format` and `Filter`.\n /// Note: This method must be used when it is known that the archive at the specified URL follows the specified\n /// `Format` and `Filter`.\n public convenience init(format: Format, filter: Filter, file: URL) throws {\n let fileHandle = try FileHandle(forReadingFrom: file)\n try self.init(format: format, filter: filter, fileHandle: fileHandle)\n }\n\n /// Initializes an `ArchiveReader` to read from the provided file descriptor with an explicit `Format` and `Filter`.\n /// Note: This method must be used when it is known that the archive pointed to by the file descriptor follows the specified\n /// `Format` and `Filter`.\n public init(format: Format, filter: Filter, fileHandle: FileHandle) throws {\n self.underlying = archive_read_new()\n self.fileHandle = fileHandle\n\n try archive_read_set_format(underlying, format.code)\n .checkOk(elseThrow: .unableToSetFormat(format.code, format))\n try archive_read_append_filter(underlying, filter.code)\n .checkOk(elseThrow: .unableToAddFilter(filter.code, filter))\n\n let fd = fileHandle.fileDescriptor\n try archive_read_open_fd(underlying, fd, 4096)\n .checkOk(elseThrow: { .unableToOpenArchive($0) })\n }\n\n /// Initialize the `ArchiveReader` to read from a specified file URL\n /// by trying to auto determine the archives `Format` and `Filter`.\n public init(file: URL) throws {\n self.underlying = archive_read_new()\n let fileHandle = try FileHandle(forReadingFrom: file)\n self.fileHandle = fileHandle\n try archive_read_support_filter_all(underlying)\n .checkOk(elseThrow: .failedToDetectFilter)\n try archive_read_support_format_all(underlying)\n .checkOk(elseThrow: .failedToDetectFormat)\n let fd = fileHandle.fileDescriptor\n try archive_read_open_fd(underlying, fd, 4096)\n .checkOk(elseThrow: { .unableToOpenArchive($0) })\n }\n\n deinit {\n archive_read_free(underlying)\n try? fileHandle?.close()\n }\n}\n\nextension CInt {\n fileprivate func checkOk(elseThrow error: @autoclosure () -> ArchiveError) throws {\n guard self == ARCHIVE_OK else { throw error() }\n }\n fileprivate func checkOk(elseThrow error: (CInt) -> ArchiveError) throws {\n guard self == ARCHIVE_OK else { throw error(self) }\n }\n\n}\n\nextension ArchiveReader: Sequence {\n public func makeIterator() -> Iterator {\n Iterator(reader: self)\n }\n\n public struct Iterator: IteratorProtocol {\n var reader: ArchiveReader\n\n public mutating func next() -> (WriteEntry, Data)? {\n let entry = WriteEntry()\n let result = archive_read_next_header2(reader.underlying, entry.underlying)\n if result == ARCHIVE_EOF {\n return nil\n }\n let data = reader.readDataForEntry(entry)\n return (entry, data)\n }\n }\n\n internal func readDataForEntry(_ entry: WriteEntry) -> Data {\n let bufferSize = Int(Swift.min(entry.size ?? 4096, 4096))\n var entry = Data()\n var part = Data(count: bufferSize)\n while true {\n let c = part.withUnsafeMutableBytes { buffer in\n guard let baseAddress = buffer.baseAddress else {\n return 0\n }\n return archive_read_data(self.underlying, baseAddress, buffer.count)\n }\n guard c > 0 else { break }\n part.count = c\n entry.append(part)\n }\n return entry\n }\n}\n\nextension ArchiveReader {\n public convenience init(name: String, bundle: Data, tempDirectoryBaseName: String? = nil) throws {\n let baseName = tempDirectoryBaseName ?? \"Unarchiver\"\n let url = createTemporaryDirectory(baseName: baseName)!.appendingPathComponent(name)\n try bundle.write(to: url, options: .atomic)\n try self.init(format: .zip, filter: .none, file: url)\n }\n\n /// Extracts the contents of an archive to the provided directory.\n /// Currently only handles regular files and directories present in the archive.\n public func extractContents(to directory: URL) throws {\n let fm = FileManager.default\n var foundEntry = false\n for (entry, data) in self {\n guard let p = entry.path else { continue }\n foundEntry = true\n let type = entry.fileType\n let target = directory.appending(path: p)\n switch type {\n case .regular:\n try data.write(to: target, options: .atomic)\n case .directory:\n try fm.createDirectory(at: target, withIntermediateDirectories: true)\n case .symbolicLink:\n guard let symlinkTarget = entry.symlinkTarget, let linkTargetURL = URL(string: symlinkTarget, relativeTo: target) else {\n continue\n }\n try fm.createSymbolicLink(at: target, withDestinationURL: linkTargetURL)\n default:\n continue\n }\n chmod(target.path(), entry.permissions)\n if let owner = entry.owner, let group = entry.group {\n chown(target.path(), owner, group)\n }\n }\n guard foundEntry else {\n throw ArchiveError.failedToExtractArchive(\"No entries found in archive\")\n }\n }\n\n /// This method extracts a given file from the archive.\n /// This operation modifies the underlying file descriptor's position within the archive,\n /// meaning subsequent reads will start from a new location.\n /// To reset the underlying file descriptor to the beginning of the archive, close and\n /// reopen the archive.\n public func extractFile(path: String) throws -> (WriteEntry, Data) {\n let entry = WriteEntry()\n while archive_read_next_header2(self.underlying, entry.underlying) != ARCHIVE_EOF {\n guard let entryPath = entry.path else { continue }\n let trimCharSet = CharacterSet(charactersIn: \"./\")\n let trimmedEntry = entryPath.trimmingCharacters(in: trimCharSet)\n let trimmedRequired = path.trimmingCharacters(in: trimCharSet)\n guard trimmedEntry == trimmedRequired else { continue }\n let data = readDataForEntry(entry)\n return (entry, data)\n }\n throw ArchiveError.failedToExtractArchive(\" \\(path) not found in archive\")\n }\n}\n"], ["/containerization/Sources/Containerization/VirtualMachineAgent.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\n/// A protocol for the agent running inside a virtual machine. If an operation isn't\n/// supported the implementation MUST return a ContainerizationError with a code of\n/// `.unsupported`.\npublic protocol VirtualMachineAgent: Sendable {\n /// Perform a platform specific standard setup\n /// of the runtime environment.\n func standardSetup() async throws\n /// Close any resources held by the agent.\n func close() async throws\n\n // POSIX\n func getenv(key: String) async throws -> String\n func setenv(key: String, value: String) async throws\n func mount(_ mount: ContainerizationOCI.Mount) async throws\n func umount(path: String, flags: Int32) async throws\n func mkdir(path: String, all: Bool, perms: UInt32) async throws\n @discardableResult\n func kill(pid: Int32, signal: Int32) async throws -> Int32\n\n // Process lifecycle\n func createProcess(\n id: String,\n containerID: String?,\n stdinPort: UInt32?,\n stdoutPort: UInt32?,\n stderrPort: UInt32?,\n configuration: ContainerizationOCI.Spec,\n options: Data?\n ) async throws\n func startProcess(id: String, containerID: String?) async throws -> Int32\n func signalProcess(id: String, containerID: String?, signal: Int32) async throws\n func resizeProcess(id: String, containerID: String?, columns: UInt32, rows: UInt32) async throws\n func waitProcess(id: String, containerID: String?, timeoutInSeconds: Int64?) async throws -> Int32\n func deleteProcess(id: String, containerID: String?) async throws\n func closeProcessStdin(id: String, containerID: String?) async throws\n\n // Networking\n func up(name: String, mtu: UInt32?) async throws\n func down(name: String) async throws\n func addressAdd(name: String, address: String) async throws\n func routeAddDefault(name: String, gateway: String) async throws\n func configureDNS(config: DNS, location: String) async throws\n func configureHosts(config: Hosts, location: String) async throws\n}\n\nextension VirtualMachineAgent {\n public func closeProcessStdin(id: String, containerID: String?) async throws {\n throw ContainerizationError(.unsupported, message: \"closeProcessStdin\")\n }\n\n public func configureHosts(config: Hosts, location: String) async throws {\n throw ContainerizationError(.unsupported, message: \"configureHosts\")\n }\n}\n"], ["/containerization/Sources/Containerization/Mount.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport Virtualization\nimport ContainerizationError\n#endif\n\n/// A filesystem mount exposed to a container.\npublic struct Mount: Sendable {\n /// The filesystem or mount type. This is the string\n /// that will be used for the mount syscall itself.\n public var type: String\n /// The source path of the mount.\n public var source: String\n /// The destination path of the mount.\n public var destination: String\n /// Filesystem or mount specific options.\n public var options: [String]\n /// Runtime specific options. This can be used\n /// as a way to discern what kind of device a vmm\n /// should create for this specific mount (virtioblock\n /// virtiofs etc.).\n public let runtimeOptions: RuntimeOptions\n\n /// A type representing a \"hint\" of what type\n /// of mount this really is (block, directory, purely\n /// guest mount) and a set of type specific options, if any.\n public enum RuntimeOptions: Sendable {\n case virtioblk([String])\n case virtiofs([String])\n case any\n }\n\n init(\n type: String,\n source: String,\n destination: String,\n options: [String],\n runtimeOptions: RuntimeOptions\n ) {\n self.type = type\n self.source = source\n self.destination = destination\n self.options = options\n self.runtimeOptions = runtimeOptions\n }\n\n /// Mount representing a virtio block device.\n public static func block(\n format: String,\n source: String,\n destination: String,\n options: [String] = [],\n runtimeOptions: [String] = []\n ) -> Self {\n .init(\n type: format,\n source: source,\n destination: destination,\n options: options,\n runtimeOptions: .virtioblk(runtimeOptions)\n )\n }\n\n /// Mount representing a virtiofs share.\n public static func share(\n source: String,\n destination: String,\n options: [String] = [],\n runtimeOptions: [String] = []\n ) -> Self {\n .init(\n type: \"virtiofs\",\n source: source,\n destination: destination,\n options: options,\n runtimeOptions: .virtiofs(runtimeOptions)\n )\n }\n\n /// A generic mount.\n public static func any(\n type: String,\n source: String,\n destination: String,\n options: [String] = []\n ) -> Self {\n .init(\n type: type,\n source: source,\n destination: destination,\n options: options,\n runtimeOptions: .any\n )\n }\n\n #if os(macOS)\n /// Clone the Mount to the provided path.\n ///\n /// This uses `clonefile` to provide a copy-on-write copy of the Mount.\n public func clone(to: String) throws -> Self {\n let fm = FileManager.default\n let src = self.source\n try fm.copyItem(atPath: src, toPath: to)\n\n return .init(\n type: self.type,\n source: to,\n destination: self.destination,\n options: self.options,\n runtimeOptions: self.runtimeOptions\n )\n }\n #endif\n}\n\n#if os(macOS)\n\nextension Mount {\n func configure(config: inout VZVirtualMachineConfiguration) throws {\n switch self.runtimeOptions {\n case .virtioblk(let options):\n let device = try VZDiskImageStorageDeviceAttachment.mountToVZAttachment(mount: self, options: options)\n let attachment = VZVirtioBlockDeviceConfiguration(attachment: device)\n config.storageDevices.append(attachment)\n case .virtiofs(_):\n guard FileManager.default.fileExists(atPath: self.source) else {\n throw ContainerizationError(.notFound, message: \"directory \\(source) does not exist\")\n }\n\n let name = try hashMountSource(source: self.source)\n let urlSource = URL(fileURLWithPath: source)\n\n let device = VZVirtioFileSystemDeviceConfiguration(tag: name)\n device.share = VZSingleDirectoryShare(\n directory: VZSharedDirectory(\n url: urlSource,\n readOnly: readonly\n )\n )\n config.directorySharingDevices.append(device)\n case .any:\n break\n }\n }\n}\n\nextension VZDiskImageStorageDeviceAttachment {\n static func mountToVZAttachment(mount: Mount, options: [String]) throws -> VZDiskImageStorageDeviceAttachment {\n var cachingMode: VZDiskImageCachingMode = .automatic\n var synchronizationMode: VZDiskImageSynchronizationMode = .none\n\n for option in options {\n let split = option.split(separator: \"=\")\n if split.count != 2 {\n continue\n }\n\n let key = String(split[0])\n let value = String(split[1])\n\n switch key {\n case \"vzDiskImageCachingMode\":\n switch value {\n case \"automatic\":\n cachingMode = .automatic\n case \"cached\":\n cachingMode = .cached\n case \"uncached\":\n cachingMode = .uncached\n default:\n throw ContainerizationError(\n .invalidArgument,\n message: \"unknown vzDiskImageCachingMode value for virtio block device: \\(value)\"\n )\n }\n case \"vzDiskImageSynchronizationMode\":\n switch value {\n case \"full\":\n synchronizationMode = .full\n case \"fsync\":\n synchronizationMode = .fsync\n case \"none\":\n synchronizationMode = .none\n default:\n throw ContainerizationError(\n .invalidArgument,\n message: \"unknown vzDiskImageSynchronizationMode value for virtio block device: \\(value)\"\n )\n }\n default:\n throw ContainerizationError(\n .invalidArgument,\n message: \"unknown vmm option encountered: \\(key)\"\n )\n }\n }\n return try VZDiskImageStorageDeviceAttachment(\n url: URL(filePath: mount.source),\n readOnly: mount.readonly,\n cachingMode: cachingMode,\n synchronizationMode: synchronizationMode\n )\n }\n}\n\n#endif\n\nextension Mount {\n fileprivate var readonly: Bool {\n self.options.contains(\"ro\")\n }\n}\n"], ["/containerization/Sources/cctl/LoginCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\nextension Application {\n struct Login: AsyncParsableCommand {\n\n static let configuration = CommandConfiguration(\n commandName: \"login\",\n abstract: \"Login to a registry\"\n )\n\n @OptionGroup() var application: Application\n\n @Option(name: .shortAndLong, help: \"Username\")\n var username: String = \"\"\n\n @Flag(help: \"Take the password from stdin\")\n var passwordStdin: Bool = false\n\n @Argument(help: \"Registry server name\")\n var server: String\n\n @Flag(help: \"Use plain text http to authenticate\") var http: Bool = false\n\n func run() async throws {\n var username = self.username\n var password = \"\"\n if passwordStdin {\n if username == \"\" {\n throw ContainerizationError(.invalidArgument, message: \"must provide --username with --password-stdin\")\n }\n guard let passwordData = try FileHandle.standardInput.readToEnd() else {\n throw ContainerizationError(.invalidArgument, message: \"failed to read password from stdin\")\n }\n password = String(decoding: passwordData, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)\n }\n let keychain = KeychainHelper(id: Application.keychainID)\n if username == \"\" {\n username = try keychain.userPrompt(domain: server)\n }\n if password == \"\" {\n password = try keychain.passwordPrompt()\n print()\n }\n\n let server = Reference.resolveDomain(domain: self.server)\n let scheme = http ? \"http\" : \"https\"\n let client = RegistryClient(\n host: server,\n scheme: scheme,\n authentication: BasicAuthentication(username: username, password: password),\n retryOptions: .init(\n maxRetries: 10,\n retryInterval: 300_000_000,\n shouldRetry: ({ response in\n response.status.code >= 500\n })\n )\n )\n try await client.ping()\n try keychain.save(domain: server, username: username, password: password)\n print(\"Login succeeded\")\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Terminal.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// `Terminal` provides a clean interface to deal with terminal interactions on Unix platforms.\npublic struct Terminal: Sendable {\n private let initState: termios?\n\n private var descriptor: Int32 {\n handle.fileDescriptor\n }\n public let handle: FileHandle\n\n public init(descriptor: Int32, setInitState: Bool = true) throws {\n if setInitState {\n self.initState = try Self.getattr(descriptor)\n } else {\n initState = nil\n }\n self.handle = .init(fileDescriptor: descriptor, closeOnDealloc: false)\n }\n\n /// Write the provided data to the tty device.\n public func write(_ data: Data) throws {\n try handle.write(contentsOf: data)\n }\n\n /// The winsize for a pty.\n public struct Size: Sendable {\n let size: winsize\n\n /// The width or `col` of the pty.\n public var width: UInt16 {\n size.ws_col\n }\n /// The height or `rows` of the pty.\n public var height: UInt16 {\n size.ws_row\n }\n\n init(_ size: winsize) {\n self.size = size\n }\n\n /// Set the size for use with a pty.\n public init(width cols: UInt16, height rows: UInt16) {\n self.size = winsize(ws_row: rows, ws_col: cols, ws_xpixel: 0, ws_ypixel: 0)\n }\n }\n\n /// Return the current pty attached to any of the STDIO descriptors.\n public static var current: Terminal {\n get throws {\n for i in [STDERR_FILENO, STDOUT_FILENO, STDIN_FILENO] {\n do {\n return try Terminal(descriptor: i)\n } catch {}\n }\n throw Error.notAPty\n }\n }\n\n /// The current window size for the pty.\n public var size: Size {\n get throws {\n var ws = winsize()\n try fromSyscall(ioctl(descriptor, UInt(TIOCGWINSZ), &ws))\n return Size(ws)\n }\n }\n\n /// Create a new pty pair.\n /// - Parameter initialSize: An initial size of the child pty.\n public static func create(initialSize: Size? = nil) throws -> (parent: Terminal, child: Terminal) {\n var parent: Int32 = 0\n var child: Int32 = 0\n let size = initialSize ?? Size(width: 120, height: 40)\n var ws = size.size\n\n try fromSyscall(openpty(&parent, &child, nil, nil, &ws))\n return (\n parent: try Terminal(descriptor: parent, setInitState: false),\n child: try Terminal(descriptor: child, setInitState: false)\n )\n }\n}\n\n// MARK: Errors\n\nextension Terminal {\n public enum Error: Swift.Error, CustomStringConvertible {\n case notAPty\n\n public var description: String {\n switch self {\n case .notAPty:\n return \"the provided fd is not a pty\"\n }\n }\n }\n}\n\nextension Terminal {\n /// Resize the current pty from the size of the provided pty.\n /// - Parameter pty: A pty to resize from.\n public func resize(from pty: Terminal) throws {\n var ws = try pty.size\n try fromSyscall(ioctl(descriptor, UInt(TIOCSWINSZ), &ws))\n }\n\n /// Resize the pty to the provided window size.\n /// - Parameter size: A window size for a pty.\n public func resize(size: Size) throws {\n var ws = size.size\n try fromSyscall(ioctl(descriptor, UInt(TIOCSWINSZ), &ws))\n }\n\n /// Resize the pty to the provided window size.\n /// - Parameter width: A width or cols of the terminal.\n /// - Parameter height: A height or rows of the terminal.\n public func resize(width: UInt16, height: UInt16) throws {\n var ws = Size(width: width, height: height)\n try fromSyscall(ioctl(descriptor, UInt(TIOCSWINSZ), &ws))\n }\n}\n\nextension Terminal {\n /// Enable raw mode for the pty.\n public func setraw() throws {\n var attr = try Self.getattr(descriptor)\n cfmakeraw(&attr)\n attr.c_oflag = attr.c_oflag | tcflag_t(OPOST)\n try fromSyscall(tcsetattr(descriptor, TCSANOW, &attr))\n }\n\n /// Enable echo support.\n /// Chars typed will be displayed to the terminal.\n public func enableEcho() throws {\n var attr = try Self.getattr(descriptor)\n attr.c_iflag &= ~tcflag_t(ICRNL)\n attr.c_lflag &= ~tcflag_t(ICANON | ECHO)\n try fromSyscall(tcsetattr(descriptor, TCSANOW, &attr))\n }\n\n /// Disable echo support.\n /// Chars typed will not be displayed back to the terminal.\n public func disableEcho() throws {\n var attr = try Self.getattr(descriptor)\n attr.c_lflag &= ~tcflag_t(ECHO)\n try fromSyscall(tcsetattr(descriptor, TCSANOW, &attr))\n }\n\n private static func getattr(_ fd: Int32) throws -> termios {\n var attr = termios()\n try fromSyscall(tcgetattr(fd, &attr))\n return attr\n }\n}\n\n// MARK: Reset\n\nextension Terminal {\n /// Close this pty's file descriptor.\n public func close() throws {\n do {\n // Use FileHandle's close directly as it sets the underlying fd in the object\n // to -1 for us.\n try self.handle.close()\n } catch {\n if let error = error as NSError?, error.domain == NSPOSIXErrorDomain {\n throw POSIXError(.init(rawValue: Int32(error.code))!)\n }\n throw error\n }\n }\n\n /// Reset the pty to its initial state.\n public func reset() throws {\n if var attr = initState {\n try fromSyscall(tcsetattr(descriptor, TCSANOW, &attr))\n }\n }\n\n /// Reset the pty to its initial state masking any errors.\n /// This is commonly used in a `defer` body to reset the current pty where the error code is not generally useful.\n public func tryReset() {\n try? reset()\n }\n}\n\nprivate func fromSyscall(_ status: Int32) throws {\n guard status == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n}\n"], ["/containerization/Sources/ContainerizationNetlink/NetlinkSession.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport ContainerizationOS\nimport Logging\n\n/// `NetlinkSession` facilitates interacting with netlink via a provided `NetlinkSocket`. This is the\n/// core high-level type offered to perform actions to the netlink surface in the kernel.\npublic struct NetlinkSession {\n private static let receiveDataLength = 65536\n private static let mtu: UInt32 = 1280\n private let socket: any NetlinkSocket\n private let log: Logger\n\n /// Creates a new `NetlinkSession`.\n /// - Parameters:\n /// - socket: The `NetlinkSocket` to use for netlink interaction.\n /// - log: The logger to use. The default value is `nil`.\n public init(socket: any NetlinkSocket, log: Logger? = nil) {\n self.socket = socket\n self.log = log ?? Logger(label: \"com.apple.containerization.netlink\")\n }\n\n /// Errors that may occur during netlink interaction.\n public enum Error: Swift.Error, CustomStringConvertible, Equatable {\n case invalidIpAddress\n case invalidPrefixLength\n case unexpectedInfo(type: UInt16)\n case unexpectedOffset(offset: Int, size: Int)\n case unexpectedResidualPackets\n case unexpectedResultSet(count: Int, expected: Int)\n\n /// The description of the errors.\n public var description: String {\n switch self {\n case .invalidIpAddress:\n return \"invalid IP address\"\n case .invalidPrefixLength:\n return \"invalid prefix length\"\n case .unexpectedInfo(let type):\n return \"unexpected response information, type = \\(type)\"\n case .unexpectedOffset(let offset, let size):\n return \"unexpected buffer state, offset = \\(offset), size = \\(size)\"\n case .unexpectedResidualPackets:\n return \"unexpected residual response packets\"\n case .unexpectedResultSet(let count, let expected):\n return \"unexpected result set size, count = \\(count), expected = \\(expected)\"\n }\n }\n }\n\n /// Performs a link set command on an interface.\n /// - Parameters:\n /// - interface: The name of the interface.\n /// - up: The value to set the interface state to.\n public func linkSet(interface: String, up: Bool, mtu: UInt32? = nil) throws {\n // ip link set dev [interface] [up|down]\n let interfaceIndex = try getInterfaceIndex(interface)\n // build the attribute only when mtu is supplied\n let attr: RTAttribute? =\n (mtu != nil)\n ? RTAttribute(\n len: UInt16(RTAttribute.size + MemoryLayout.size),\n type: LinkAttributeType.IFLA_MTU)\n : nil\n let requestSize = NetlinkMessageHeader.size + InterfaceInfo.size + (attr?.paddedLen ?? 0)\n var requestBuffer = [UInt8](repeating: 0, count: requestSize)\n var requestOffset = 0\n\n let requestHeader = NetlinkMessageHeader(\n len: UInt32(requestBuffer.count),\n type: NetlinkType.RTM_NEWLINK,\n flags: NetlinkFlags.NLM_F_REQUEST | NetlinkFlags.NLM_F_ACK,\n pid: socket.pid)\n requestOffset = try requestHeader.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let flags = up ? InterfaceFlags.IFF_UP : 0\n let requestInfo = InterfaceInfo(\n family: UInt8(AddressFamily.AF_PACKET),\n index: interfaceIndex,\n flags: flags,\n change: InterfaceFlags.DEFAULT_CHANGE)\n requestOffset = try requestInfo.appendBuffer(&requestBuffer, offset: requestOffset)\n\n if let attr = attr, let m = mtu {\n requestOffset = try attr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard\n let newRequestOffset =\n requestBuffer.copyIn(as: UInt32.self, value: m, offset: requestOffset)\n else {\n throw NetlinkDataError.sendMarshalFailure\n }\n requestOffset = newRequestOffset\n }\n\n guard requestOffset == requestSize else {\n throw Error.unexpectedOffset(offset: requestOffset, size: requestSize)\n }\n\n try sendRequest(buffer: &requestBuffer)\n let (infos, _) = try parseResponse(infoType: NetlinkType.RTM_NEWLINK) { InterfaceInfo() }\n guard infos.count == 0 else {\n throw Error.unexpectedResultSet(count: infos.count, expected: 0)\n }\n }\n\n /// Performs a link get command on an interface.\n /// Returns information about the interface.\n /// - Parameter interface: The name of the interface to query.\n public func linkGet(interface: String? = nil) throws -> [LinkResponse] {\n // ip link ip show\n let maskAttr = RTAttribute(\n len: UInt16(RTAttribute.size + MemoryLayout.size), type: LinkAttributeType.IFLA_EXT_MASK)\n let interfaceName = try interface.map { try getInterfaceName($0) }\n let interfaceNameAttr = interfaceName.map {\n RTAttribute(len: UInt16(RTAttribute.size + $0.count), type: LinkAttributeType.IFLA_EXT_IFNAME)\n }\n let requestSize =\n NetlinkMessageHeader.size + InterfaceInfo.size + maskAttr.paddedLen + (interfaceNameAttr?.paddedLen ?? 0)\n var requestBuffer = [UInt8](repeating: 0, count: requestSize)\n var requestOffset = 0\n\n let flags =\n interface != nil ? NetlinkFlags.NLM_F_REQUEST : (NetlinkFlags.NLM_F_REQUEST | NetlinkFlags.NLM_F_DUMP)\n let requestHeader = NetlinkMessageHeader(\n len: UInt32(requestBuffer.count),\n type: NetlinkType.RTM_GETLINK,\n flags: flags,\n pid: socket.pid)\n requestOffset = try requestHeader.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let requestInfo = InterfaceInfo(\n family: UInt8(AddressFamily.AF_PACKET),\n index: 0,\n flags: InterfaceFlags.IFF_UP,\n change: InterfaceFlags.DEFAULT_CHANGE)\n requestOffset = try requestInfo.appendBuffer(&requestBuffer, offset: requestOffset)\n\n requestOffset = try maskAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard\n var requestOffset = requestBuffer.copyIn(\n as: UInt32.self,\n value: LinkAttributeMaskFilter.RTEXT_FILTER_VF | LinkAttributeMaskFilter.RTEXT_FILTER_SKIP_STATS,\n offset: requestOffset)\n else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n if let interfaceNameAttr {\n if let interfaceName {\n requestOffset = try interfaceNameAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard let updatedRequestOffset = requestBuffer.copyIn(buffer: interfaceName, offset: requestOffset)\n else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n requestOffset = updatedRequestOffset\n }\n }\n\n guard requestOffset == requestSize else {\n throw Error.unexpectedOffset(offset: requestOffset, size: requestSize)\n }\n\n try sendRequest(buffer: &requestBuffer)\n let (infos, attrDataLists) = try parseResponse(infoType: NetlinkType.RTM_NEWLINK) { InterfaceInfo() }\n var linkResponses: [LinkResponse] = []\n for i in 0...size * ipAddressBytes.count\n let requestSize = NetlinkMessageHeader.size + AddressInfo.size + 2 * addressAttrSize\n var requestBuffer = [UInt8](repeating: 0, count: requestSize)\n var requestOffset = 0\n\n let header = NetlinkMessageHeader(\n len: UInt32(requestBuffer.count),\n type: NetlinkType.RTM_NEWADDR,\n flags: NetlinkFlags.NLM_F_REQUEST | NetlinkFlags.NLM_F_ACK | NetlinkFlags.NLM_F_EXCL\n | NetlinkFlags.NLM_F_CREATE,\n seq: 0,\n pid: socket.pid)\n requestOffset = try header.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let requestInfo = AddressInfo(\n family: UInt8(AddressFamily.AF_INET),\n prefixLength: parsed.prefix,\n flags: 0,\n scope: NetlinkScope.RT_SCOPE_UNIVERSE,\n index: UInt32(interfaceIndex))\n requestOffset = try requestInfo.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let ipLocalAttr = RTAttribute(len: UInt16(addressAttrSize), type: AddressAttributeType.IFA_LOCAL)\n requestOffset = try ipLocalAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard var requestOffset = requestBuffer.copyIn(buffer: ipAddressBytes, offset: requestOffset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n let ipAddressAttr = RTAttribute(len: UInt16(addressAttrSize), type: AddressAttributeType.IFA_ADDRESS)\n requestOffset = try ipAddressAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard let requestOffset = requestBuffer.copyIn(buffer: ipAddressBytes, offset: requestOffset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n guard requestOffset == requestSize else {\n throw Error.unexpectedOffset(offset: requestOffset, size: requestSize)\n }\n\n try sendRequest(buffer: &requestBuffer)\n let (infos, _) = try parseResponse(infoType: NetlinkType.RTM_NEWLINK) { AddressInfo() }\n guard infos.count == 0 else {\n throw Error.unexpectedResultSet(count: infos.count, expected: 0)\n }\n }\n\n private func parseCIDR(cidr: String) throws -> (address: String, prefix: UInt8) {\n let split = cidr.components(separatedBy: \"/\")\n guard split.count == 2 else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n let address = split[0]\n guard let prefixLength = PrefixLength(split[1]) else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n guard prefixLength >= 0 && prefixLength <= 32 else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n return (address, prefixLength)\n }\n\n /// Adds a route to an interface.\n /// - Parameters:\n /// - interface: The name of the interface.\n /// - destinationAddress: The destination address to route to.\n /// - srcAddr: The source address to route from.\n public func routeAdd(\n interface: String,\n destinationAddress: String,\n srcAddr: String\n ) throws {\n // ip route add [dest-cidr] dev [interface] src [src-addr] proto kernel\n let parsed = try parseCIDR(cidr: destinationAddress)\n let interfaceIndex = try getInterfaceIndex(interface)\n let dstAddrBytes = try IPv4Address(parsed.address).networkBytes\n let dstAddrAttrSize = RTAttribute.size + dstAddrBytes.count\n let srcAddrBytes = try IPv4Address(srcAddr).networkBytes\n let srcAddrAttrSize = RTAttribute.size + srcAddrBytes.count\n let interfaceAttrSize = RTAttribute.size + MemoryLayout.size\n let requestSize =\n NetlinkMessageHeader.size + RouteInfo.size + dstAddrAttrSize + srcAddrAttrSize + interfaceAttrSize\n var requestBuffer = [UInt8](repeating: 0, count: requestSize)\n var requestOffset = 0\n\n let header = NetlinkMessageHeader(\n len: UInt32(requestBuffer.count),\n type: NetlinkType.RTM_NEWROUTE,\n flags: NetlinkFlags.NLM_F_REQUEST | NetlinkFlags.NLM_F_ACK | NetlinkFlags.NLM_F_EXCL\n | NetlinkFlags.NLM_F_CREATE,\n pid: socket.pid)\n requestOffset = try header.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let requestInfo = RouteInfo(\n family: UInt8(AddressFamily.AF_INET),\n dstLen: parsed.prefix,\n srcLen: 0,\n tos: 0,\n table: RouteTable.MAIN,\n proto: RouteProtocol.KERNEL,\n scope: RouteScope.LINK,\n type: RouteType.UNICAST,\n flags: 0)\n requestOffset = try requestInfo.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let dstAddrAttr = RTAttribute(len: UInt16(dstAddrAttrSize), type: RouteAttributeType.DST)\n requestOffset = try dstAddrAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard var requestOffset = requestBuffer.copyIn(buffer: dstAddrBytes, offset: requestOffset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n let srcAddrAttr = RTAttribute(len: UInt16(dstAddrAttrSize), type: RouteAttributeType.PREFSRC)\n requestOffset = try srcAddrAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard var requestOffset = requestBuffer.copyIn(buffer: srcAddrBytes, offset: requestOffset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n let interfaceAttr = RTAttribute(len: UInt16(interfaceAttrSize), type: RouteAttributeType.OIF)\n requestOffset = try interfaceAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard\n let requestOffset = requestBuffer.copyIn(\n as: UInt32.self,\n value: UInt32(interfaceIndex),\n offset: requestOffset)\n else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n guard requestOffset == requestSize else {\n throw Error.unexpectedOffset(offset: requestOffset, size: requestSize)\n }\n\n try sendRequest(buffer: &requestBuffer)\n let (infos, _) = try parseResponse(infoType: NetlinkType.RTM_NEWLINK) { AddressInfo() }\n guard infos.count == 0 else {\n throw Error.unexpectedResultSet(count: infos.count, expected: 0)\n }\n }\n\n /// Adds a default route to an interface.\n /// - Parameters:\n /// - interface: The name of the interface.\n /// - gateway: The gateway address.\n public func routeAddDefault(\n interface: String,\n gateway: String\n ) throws {\n // ip route add default via [dst-address] src [src-address]\n let dstAddrBytes = try IPv4Address(gateway).networkBytes\n let dstAddrAttrSize = RTAttribute.size + dstAddrBytes.count\n\n let interfaceAttrSize = RTAttribute.size + MemoryLayout.size\n let interfaceIndex = try getInterfaceIndex(interface)\n let requestSize = NetlinkMessageHeader.size + RouteInfo.size + dstAddrAttrSize + interfaceAttrSize\n\n var requestBuffer = [UInt8](repeating: 0, count: requestSize)\n var requestOffset = 0\n\n let header = NetlinkMessageHeader(\n len: UInt32(requestBuffer.count),\n type: NetlinkType.RTM_NEWROUTE,\n flags: NetlinkFlags.NLM_F_REQUEST | NetlinkFlags.NLM_F_ACK | NetlinkFlags.NLM_F_EXCL\n | NetlinkFlags.NLM_F_CREATE,\n pid: socket.pid)\n requestOffset = try header.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let requestInfo = RouteInfo(\n family: UInt8(AddressFamily.AF_INET),\n dstLen: 0,\n srcLen: 0,\n tos: 0,\n table: RouteTable.MAIN,\n proto: RouteProtocol.BOOT,\n scope: RouteScope.UNIVERSE,\n type: RouteType.UNICAST,\n flags: 0)\n requestOffset = try requestInfo.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let dstAddrAttr = RTAttribute(len: UInt16(dstAddrAttrSize), type: RouteAttributeType.GATEWAY)\n requestOffset = try dstAddrAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard var requestOffset = requestBuffer.copyIn(buffer: dstAddrBytes, offset: requestOffset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n let interfaceAttr = RTAttribute(len: UInt16(interfaceAttrSize), type: RouteAttributeType.OIF)\n requestOffset = try interfaceAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard\n let requestOffset = requestBuffer.copyIn(\n as: UInt32.self,\n value: UInt32(interfaceIndex),\n offset: requestOffset)\n else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n guard requestOffset == requestSize else {\n throw Error.unexpectedOffset(offset: requestOffset, size: requestSize)\n }\n\n try sendRequest(buffer: &requestBuffer)\n let (infos, _) = try parseResponse(infoType: NetlinkType.RTM_NEWLINK) { AddressInfo() }\n guard infos.count == 0 else {\n throw Error.unexpectedResultSet(count: infos.count, expected: 0)\n }\n }\n\n private func getInterfaceName(_ interface: String) throws -> [UInt8] {\n guard let interfaceNameData = interface.data(using: .utf8) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n var interfaceName = [UInt8](interfaceNameData)\n interfaceName.append(0)\n\n while interfaceName.count % MemoryLayout.size != 0 {\n interfaceName.append(0)\n }\n\n return interfaceName\n }\n\n private func getInterfaceIndex(_ interface: String) throws -> Int32 {\n let linkResponses = try linkGet(interface: interface)\n guard linkResponses.count == 1 else {\n throw Error.unexpectedResultSet(count: linkResponses.count, expected: 1)\n }\n\n return linkResponses[0].interfaceIndex\n }\n\n private func sendRequest(buffer: inout [UInt8]) throws {\n log.trace(\"SEND-LENGTH: \\(buffer.count)\")\n log.trace(\"SEND-DUMP: \\(buffer[0.. ([UInt8], Int) {\n var buffer = [UInt8](repeating: 0, count: Self.receiveDataLength)\n let size = try socket.recv(buf: &buffer, len: Self.receiveDataLength, flags: 0)\n log.trace(\"RECV-LENGTH: \\(size)\")\n log.trace(\"RECV-DUMP: \\(buffer[0..(infoType: UInt16? = nil, _ infoProvider: () -> T) throws -> (\n [T], [[RTAttributeData]]\n ) {\n var infos: [T] = []\n var attrDataLists: [[RTAttributeData]] = []\n\n var moreResponses = false\n repeat {\n var (buffer, size) = try receiveResponse()\n let header: NetlinkMessageHeader\n var offset = 0\n\n (header, offset) = try parseHeader(buffer: &buffer, offset: offset)\n if let infoType {\n if header.type == infoType {\n log.trace(\n \"RECV-INFO-DUMP: dump = \\(buffer[offset.. (Int32, Int) {\n guard let errorPtr = buffer.bind(as: Int32.self, offset: offset) else {\n throw NetlinkDataError.recvUnmarshalFailure\n }\n\n let rc = errorPtr.pointee\n log.trace(\"RECV-ERR-CODE: \\(rc)\")\n\n return (rc, offset + MemoryLayout.size)\n }\n\n private func parseErrorResponse(buffer: inout [UInt8], offset: Int) throws -> Int {\n var (rc, offset) = try parseErrorCode(buffer: &buffer, offset: offset)\n log.trace(\n \"RECV-ERR-HEADER-DUMP: dump = \\(buffer[offset.. (NetlinkMessageHeader, Int) {\n log.trace(\"RECV-HEADER-DUMP: dump = \\(buffer[offset.. (\n [RTAttributeData], Int\n ) {\n var attrDatas: [RTAttributeData] = []\n var offset = offset\n var residualCount = residualCount\n log.trace(\"RECV-RESIDUAL: \\(residualCount)\")\n\n while residualCount > 0 {\n var attr = RTAttribute()\n log.trace(\" RECV-ATTR-DUMP: dump = \\(buffer[offset..= 0 {\n log.trace(\" RECV-ATTR-DATA-DUMP: dump = \\(buffer[offset.. {\n let (stream, cont) = AsyncStream.makeStream(of: Int32.self)\n self.state.withLock {\n $0.conts.append(cont)\n }\n cont.onTermination = { @Sendable _ in\n self.cancel()\n }\n return stream\n }\n\n /// Cancel every AsyncStream of signals, as well as the underlying\n /// DispatchSignalSource's for each registered signal.\n public func cancel() {\n self.state.withLock {\n if $0.conts.isEmpty {\n return\n }\n\n for cont in $0.conts {\n cont.finish()\n }\n for source in $0.sources {\n source.cancel()\n }\n $0.conts.removeAll()\n $0.sources.removeAll()\n }\n }\n\n struct State: Sendable {\n var conts: [AsyncStream.Continuation] = []\n nonisolated(unsafe) var sources: [any DispatchSourceSignal] = []\n }\n\n // We keep a reference to the continuation object that is created for\n // our AsyncStream and tell our signal handler to yield a value to it\n // returning a value to the consumer\n private func handler(_ sig: Int32) {\n self.state.withLock {\n for cont in $0.conts {\n cont.yield(sig)\n }\n }\n }\n\n private let state: Mutex = .init(State())\n\n /// Create a new `AsyncSignalHandler` for the list of given signals `notify`.\n /// The default signal handlers for these signals are removed and async handlers\n /// added in their place. The async signal handlers that are installed simply\n /// yield to a stream if and when a signal is caught.\n public static func create(notify on: [Int32]) -> AsyncSignalHandler {\n let out = AsyncSignalHandler()\n var sources = [any DispatchSourceSignal]()\n for sig in on {\n signal(sig, SIG_IGN)\n let source = DispatchSource.makeSignalSource(signal: sig)\n source.setEventHandler {\n out.handler(sig)\n }\n source.resume()\n // Retain a reference to our signal sources so that they\n // do not go out of scope.\n sources.append(source)\n }\n out.state.withLock { $0.sources = sources }\n return out\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/User.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\n\n/// `User` provides utilities to ensure that a given username exists in\n/// /etc/passwd (and /etc/group).\npublic enum User {\n private static let passwdFile = \"/etc/passwd\"\n private static let groupFile = \"/etc/group\"\n\n public struct ExecUser: Sendable {\n public var uid: UInt32\n public var gid: UInt32\n public var sgids: [UInt32]\n public var home: String\n }\n\n private struct User {\n let name: String\n let password: String\n let uid: UInt32\n let gid: UInt32\n let gecos: String\n let home: String\n let shell: String\n\n /// The argument `rawString` must follow the below format.\n /// Name:Password:Uid:Gid:Gecos:Home:Shell\n init(rawString: String) throws {\n let args = rawString.split(separator: \":\", omittingEmptySubsequences: false)\n guard args.count == 7 else {\n throw ContainerizationError.init(.invalidArgument, message: \"Cannot parse User from '\\(rawString)'\")\n }\n guard let uid = UInt32(args[2]) else {\n throw ContainerizationError.init(.invalidArgument, message: \"Cannot parse uid from '\\(args[2])'\")\n }\n guard let gid = UInt32(args[3]) else {\n throw ContainerizationError.init(.invalidArgument, message: \"Cannot parse gid from '\\(args[3])'\")\n }\n self.name = String(args[0])\n self.password = String(args[1])\n self.uid = uid\n self.gid = gid\n self.gecos = String(args[4])\n self.home = String(args[5])\n self.shell = String(args[6])\n }\n }\n\n private struct Group {\n let name: String\n let password: String\n let gid: UInt32\n let users: [String]\n\n /// The argument `rawString` must follow the below format.\n /// Name:Password:Gid:user1,user2\n init(rawString: String) throws {\n let args = rawString.split(separator: \":\", omittingEmptySubsequences: false)\n guard args.count == 4 else {\n throw ContainerizationError.init(.invalidArgument, message: \"Cannot parse Group from '\\(rawString)'\")\n }\n guard let gid = UInt32(args[2]) else {\n throw ContainerizationError.init(.invalidArgument, message: \"Cannot parse gid from '\\(args[2])'\")\n }\n self.name = String(args[0])\n self.password = String(args[1])\n self.gid = gid\n self.users = args[3].split(separator: \",\").map { String($0) }\n }\n }\n}\n\n// MARK: Private methods\n\nextension User {\n /// Parse the contents of the passwd file\n private static func parsePasswd(passwdFile: URL) throws -> [User] {\n var users: [User] = []\n try self.parse(file: passwdFile) { line in\n let user = try User(rawString: line)\n users.append(user)\n }\n return users\n }\n\n /// Parse the contents of the group file\n private static func parseGroup(groupFile: URL) throws -> [Group] {\n var groups: [Group] = []\n try self.parse(file: groupFile) { line in\n let group = try Group(rawString: line)\n groups.append(group)\n }\n return groups\n }\n\n private static func parse(file: URL, handler: (_ line: String) throws -> Void) throws {\n let fm = FileManager.default\n guard fm.fileExists(atPath: file.absolutePath()) else {\n throw ContainerizationError(.notFound, message: \"File \\(file.absolutePath()) does not exist\")\n }\n let content = try String(contentsOf: file, encoding: .ascii)\n let lines = content.components(separatedBy: .newlines)\n for line in lines {\n guard !line.isEmpty else {\n continue\n }\n try handler(line.trimmingCharacters(in: .whitespaces))\n }\n }\n}\n\n// MARK: Public methods\n\nextension User {\n public static func parseUser(root: String, userString: String) throws -> ExecUser {\n let defaultUser = ExecUser(uid: 0, gid: 0, sgids: [], home: \"/\")\n guard !userString.isEmpty else {\n return defaultUser\n }\n\n let passwdPath = URL(filePath: root).appending(path: Self.passwdFile)\n let groupPath = URL(filePath: root).appending(path: Self.groupFile)\n let parts = userString.split(separator: \":\", maxSplits: 1, omittingEmptySubsequences: false)\n\n let userArg = String(parts[0])\n let userIdArg = Int(userArg)\n\n guard FileManager.default.fileExists(atPath: passwdPath.absolutePath()) else {\n guard let userIdArg else {\n throw ContainerizationError(.internalError, message: \"Cannot parse username \\(userArg)\")\n }\n let uid = UInt32(userIdArg)\n guard parts.count > 1 else {\n return ExecUser(uid: uid, gid: uid, sgids: [], home: \"/\")\n }\n guard let gid = UInt32(String(parts[1])) else {\n throw ContainerizationError(.internalError, message: \"Cannot parse user group from \\(userString)\")\n }\n return ExecUser(uid: uid, gid: gid, sgids: [], home: \"/\")\n }\n\n let registeredUsers = try parsePasswd(passwdFile: passwdPath)\n guard registeredUsers.count > 0 else {\n throw ContainerizationError(.internalError, message: \"No users configured in passwd file.\")\n }\n let matches = registeredUsers.filter { registeredUser in\n // Check for a match (either uid/name) against the configured users from the passwd file.\n // We have to check both the uid and the name cause we dont know the type of `userString`\n registeredUser.name == userArg || registeredUser.uid == (userIdArg ?? -1)\n }\n guard let match = matches.first else {\n // We did not find a matching uid/username in the passwd file\n throw ContainerizationError(.internalError, message: \"Cannot find User '\\(userArg)' in passwd file.\")\n }\n\n var user = ExecUser(uid: match.uid, gid: match.gid, sgids: [match.gid], home: match.home)\n\n guard !match.name.isEmpty else {\n return user\n }\n let matchedUser = match.name\n var groupArg = \"\"\n var groupIdArg: Int? = nil\n if parts.count > 1 {\n groupArg = String(parts[1])\n groupIdArg = Int(groupArg)\n }\n\n let registeredGroups: [Group] = {\n do {\n // Parse the /etc/group file for a list of registered groups.\n // If the file is missing / malformed, we bail out\n return try parseGroup(groupFile: groupPath)\n } catch {\n return []\n }\n }()\n guard registeredGroups.count > 0 else {\n return user\n }\n let matchingGroups = registeredGroups.filter { registeredGroup in\n if !groupArg.isEmpty {\n return registeredGroup.gid == (groupIdArg ?? -1) || registeredGroup.name == groupArg\n }\n return registeredGroup.users.contains(matchedUser) || registeredGroup.gid == match.gid\n }\n guard matchingGroups.count > 0 else {\n throw ContainerizationError(.internalError, message: \"Cannot find Group '\\(groupArg)' in groups file.\")\n }\n // We have found a list of groups that match the group specified in the argument `userString`.\n // Set the matched groups as the supplement groups for the user\n if !groupArg.isEmpty {\n // Reassign the user's group only we were explicitly asked for a group\n user.gid = matchingGroups.first!.gid\n user.sgids = matchingGroups.map { group in\n group.gid\n }\n } else {\n user.sgids.append(\n contentsOf: matchingGroups.map { group in\n group.gid\n })\n }\n return user\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Reference.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\n\nprivate let referenceTotalLengthMax = 255\nprivate let nameTotalLengthMax = 127\nprivate let legacyDockerRegistryHost = \"docker.io\"\nprivate let dockerRegistryHost = \"registry-1.docker.io\"\nprivate let defaultDockerRegistryRepo = \"library\"\nprivate let defaultTag = \"latest\"\n\n/// A Reference is composed of the various parts of an OCI image reference.\n/// For example:\n/// let imageReference = \"my-registry.com/repository/image:tag2\"\n/// let reference = Reference.parse(imageReference)\n/// print(reference.domain!) // gives us \"my-registry.com\"\n/// print(reference.name) // gives us \"my-registry.com/repository/image\"\n/// print(reference.path) // gives us \"repository/image\"\n/// print(reference.tag!) // gives us \"tag2\"\n/// print(reference.digest) // gives us \"nil\"\npublic class Reference: CustomStringConvertible {\n private var _domain: String?\n public var domain: String? {\n _domain\n }\n public var resolvedDomain: String? {\n if let d = _domain {\n return Self.resolveDomain(domain: d)\n }\n return nil\n }\n\n private var _path: String\n public var path: String {\n _path\n }\n\n private var _tag: String?\n public var tag: String? {\n _tag\n }\n\n private var _digest: String?\n public var digest: String? {\n _digest\n }\n\n public var name: String {\n if let domain, !domain.isEmpty {\n return \"\\(domain)/\\(path)\"\n }\n return path\n }\n\n public var description: String {\n if let tag {\n return \"\\(name):\\(tag)\"\n }\n if let digest {\n return \"\\(name)@\\(digest)\"\n }\n return name\n }\n\n static let identifierPattern = \"([a-f0-9]{64})\"\n\n static let domainPattern = {\n let domainNameComponent = \"(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])\"\n let optionalPort = \"(?::[0-9]+)?\"\n let ipv6address = \"\\\\[(?:[a-fA-F0-9:]+)\\\\]\"\n let domainName = \"\\(domainNameComponent)(?:\\\\.\\(domainNameComponent))*\"\n let host = \"(?:\\(domainName)|\\(ipv6address))\"\n let domainAndPort = \"\\(host)\\(optionalPort)\"\n return domainAndPort\n }()\n\n static let pathPattern = \"(?(?:[a-z0-9]+(?:[._]|__|-|/)?)*[a-z0-9]+)\"\n static let tagPattern = \"(?::(?[\\\\w][\\\\w.-]{0,127}))?(?:@(?sha256:[0-9a-fA-F]{64}))?\"\n static let pathTagPattern = \"\\(pathPattern)\\(tagPattern)\"\n\n public init(path: String, domain: String? = nil, tag: String? = nil, digest: String? = nil) throws {\n if let domain, !domain.isEmpty {\n self._domain = domain\n }\n\n self._path = path\n self._tag = tag\n self._digest = digest\n }\n\n public static func parse(_ s: String) throws -> Reference {\n if s.count > referenceTotalLengthMax {\n throw ContainerizationError(.invalidArgument, message: \"Reference length \\(s.count) greater than \\(referenceTotalLengthMax)\")\n }\n\n let identifierRegex = try Regex(Self.identifierPattern)\n guard try identifierRegex.wholeMatch(in: s) == nil else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot specify 64 byte hex string as reference\")\n }\n\n let (domain, remainder) = try Self.parseDomain(from: s)\n let constructedRawReference: String = remainder\n if let domain {\n let domainRegex = try Regex(domainPattern)\n guard try domainRegex.wholeMatch(in: domain) != nil else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid domain \\(domain) for reference \\(s)\")\n }\n }\n let fields = try constructedRawReference.matches(regex: pathTagPattern)\n guard let path = fields[\"path\"] else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot parse path for reference \\(s)\")\n }\n\n let ref = try Reference(path: path, domain: domain)\n if ref.name.count > nameTotalLengthMax {\n throw ContainerizationError(.invalidArgument, message: \"Repo length \\(ref.name.count) greater than \\(nameTotalLengthMax)\")\n }\n\n // Extract tag and digest\n let tag = fields[\"tag\"] ?? \"\"\n let digest = fields[\"digest\"] ?? \"\"\n\n if !digest.isEmpty {\n return try ref.withDigest(digest)\n } else if !tag.isEmpty {\n return try ref.withTag(tag)\n }\n return ref\n }\n\n private static func parseDomain(from s: String) throws -> (domain: String?, remainder: String) {\n var domain: String? = nil\n var path: String = s\n let charset = CharacterSet(charactersIn: \".:\")\n let splits = s.split(separator: \"/\", maxSplits: 1)\n guard splits.count == 2 else {\n if s.starts(with: \"localhost\") {\n return (s, \"\")\n }\n return (nil, s)\n }\n let _domain = String(splits[0])\n let _path = String(splits[1])\n if _domain.starts(with: \"localhost\") || _domain.rangeOfCharacter(from: charset) != nil {\n domain = _domain\n path = _path\n }\n return (domain, path)\n }\n\n public static func withName(_ name: String) throws -> Reference {\n if name.count > nameTotalLengthMax {\n throw ContainerizationError(.invalidArgument, message: \"Name length \\(name.count) greater than \\(nameTotalLengthMax)\")\n }\n let fields = try name.matches(regex: Self.domainPattern)\n // Extract domain and path\n let domain = fields[\"domain\"] ?? \"\"\n let path = fields[\"path\"] ?? \"\"\n\n if domain.isEmpty || path.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Image reference domain or path is empty\")\n }\n\n return try Reference(path: path, domain: domain)\n }\n\n public func withTag(_ tag: String) throws -> Reference {\n var tag = tag\n if !tag.starts(with: \":\") {\n tag = \":\" + tag\n }\n let fields = try tag.matches(regex: Self.tagPattern)\n tag = fields[\"tag\"] ?? \"\"\n\n if tag.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Invalid format for image reference. Missing tag\")\n }\n return try Reference(path: self.path, domain: self.domain, tag: tag)\n }\n\n public func withDigest(_ digest: String) throws -> Reference {\n var digest = digest\n if !digest.starts(with: \"@\") {\n digest = \"@\" + digest\n }\n let fields = try digest.matches(regex: Self.tagPattern)\n digest = fields[\"digest\"] ?? \"\"\n\n if digest.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Invalid format for image reference. Missing digest\")\n }\n return try Reference(path: self.path, domain: self.domain, digest: digest)\n }\n\n private static func splitDomain(_ name: String) -> (domain: String, path: String) {\n let parts = name.split(separator: \"/\")\n guard parts.count == 2 else {\n return (\"\", name)\n }\n return (String(parts[0]), String(parts[1]))\n }\n\n /// Normalize the reference object.\n /// Normalization is useful in cases where the reference object is to be used to\n /// fetch/push an image from/to a remote registry.\n /// It does the following:\n /// - Adds a default tag of \"latest\" if the reference had no tag/digest set.\n /// - If the domain is \"registry-1.docker.io\" or \"docker.io\" and the path has no repository set,\n /// it adds a default \"library/\" repository name.\n public func normalize() {\n if let domain = self.domain, domain == dockerRegistryHost || domain == legacyDockerRegistryHost {\n // Check if the image is being referenced by a named tag.\n // If it is, and a repository is not specified, prefix it with \"library/\".\n // This needs to be done only if we are using the Docker registry.\n if !self.path.contains(\"/\") {\n self._path = \"\\(defaultDockerRegistryRepo)/\\(self._path)\"\n }\n }\n let identifier = self._tag ?? self._digest\n if identifier == nil {\n // If the user did not specify a tag or a digest for the reference, set the tag to \"latest\".\n self._tag = defaultTag\n }\n }\n\n public static func resolveDomain(domain: String) -> String {\n if domain == legacyDockerRegistryHost {\n return dockerRegistryHost\n }\n return domain\n }\n}\n\nextension String {\n func matches(regex: String) throws -> [String: String] {\n do {\n let regex = try NSRegularExpression(pattern: regex, options: [])\n let nsRange = NSRange(self.startIndex.. [String] {\n let pattern = self.pattern\n let regex = try NSRegularExpression(pattern: \"\\\\(\\\\?<(\\\\w+)>\", options: [])\n let nsRange = NSRange(pattern.startIndex.. String? {\n if let t = token ?? accessToken {\n return \"Bearer \\(t)\"\n }\n return nil\n }\n\n func isValid(scope: String?) -> Bool {\n guard let issuedAt else {\n return false\n }\n let isoFormatter = ISO8601DateFormatter()\n isoFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]\n guard let issued = isoFormatter.date(from: issuedAt) else {\n return false\n }\n let expiresIn = expiresIn ?? 0\n let now = Date()\n let elapsed = now.timeIntervalSince(issued)\n guard elapsed < Double(expiresIn) else {\n return false\n }\n if let requiredScope = scope {\n return requiredScope == self.scope\n }\n return false\n }\n}\n\nstruct AuthenticateChallenge: Equatable {\n let type: String\n let realm: String?\n let service: String?\n let scope: String?\n let error: String?\n\n init(type: String, realm: String?, service: String?, scope: String?, error: String?) {\n self.type = type\n self.realm = realm\n self.service = service\n self.scope = scope\n self.error = error\n }\n\n init(type: String, values: [String: String]) {\n self.type = type\n self.realm = values[\"realm\"]\n self.service = values[\"service\"]\n self.scope = values[\"scope\"]\n self.error = values[\"error\"]\n }\n}\n\nextension RegistryClient {\n /// Fetch an auto token for all subsequent HTTP requests\n /// See https://docs.docker.com/registry/spec/auth/token/\n internal func fetchToken(request: TokenRequest) async throws -> TokenResponse {\n guard var components = URLComponents(string: request.realm) else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot create URL from \\(request.realm)\")\n }\n components.queryItems = [\n URLQueryItem(name: \"client_id\", value: request.clientId),\n URLQueryItem(name: \"service\", value: request.service),\n ]\n var scope = \"\"\n if let reqScope = request.scope {\n scope = reqScope\n components.queryItems?.append(URLQueryItem(name: \"scope\", value: reqScope))\n }\n\n if request.offlineToken {\n components.queryItems?.append(URLQueryItem(name: \"offline_token\", value: \"true\"))\n }\n var response: TokenResponse = try await requestJSON(components: components, headers: [])\n response.scope = scope\n return response\n }\n\n internal func createTokenRequest(parsing authenticateHeaders: [String]) throws -> TokenRequest {\n let parsedHeaders = Self.parseWWWAuthenticateHeaders(headers: authenticateHeaders)\n let bearerChallenge = parsedHeaders.first { $0.type == \"Bearer\" }\n guard let bearerChallenge else {\n throw ContainerizationError(.invalidArgument, message: \"Missing Bearer challenge in \\(TokenRequest.authenticateHeaderName) header\")\n }\n guard let realm = bearerChallenge.realm else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot parse realm from \\(TokenRequest.authenticateHeaderName) header\")\n }\n guard let service = bearerChallenge.service else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot parse service from \\(TokenRequest.authenticateHeaderName) header\")\n }\n let scope = bearerChallenge.scope\n let tokenRequest = TokenRequest(realm: realm, service: service, clientId: self.clientID, scope: scope, authentication: self.authentication)\n return tokenRequest\n }\n\n internal static func parseWWWAuthenticateHeaders(headers: [String]) -> [AuthenticateChallenge] {\n var parsed: [String: [String: String]] = [:]\n for challenge in headers {\n let trimmedChallenge = challenge.trimmingCharacters(in: .whitespacesAndNewlines)\n let parts = trimmedChallenge.split(separator: \" \", maxSplits: 1)\n guard parts.count == 2 else {\n continue\n }\n guard let scheme = parts.first else {\n continue\n }\n var params: [String: String] = [:]\n let header = String(parts[1])\n let pattern = #\"(\\w+)=\"([^\"]+)\"#\n let regex = try! NSRegularExpression(pattern: pattern, options: [])\n let matches = regex.matches(in: header, options: [], range: NSRange(header.startIndex..., in: header))\n for match in matches {\n if let keyRange = Range(match.range(at: 1), in: header),\n let valueRange = Range(match.range(at: 2), in: header)\n {\n let key = String(header[keyRange])\n let value = String(header[valueRange])\n params[key] = value\n }\n }\n parsed[String(scheme)] = params\n }\n var parsedChallenges: [AuthenticateChallenge] = []\n for (type, values) in parsed {\n parsedChallenges.append(.init(type: type, values: values))\n }\n return parsedChallenges\n }\n}\n"], ["/containerization/Sources/Integration/VMTests.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport Logging\n\nextension IntegrationSuite {\n func testMounts() async throws {\n let id = \"test-cat-mount\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n let directory = try createMountDirectory()\n config.process.arguments = [\"/bin/cat\", \"/mnt/hi.txt\"]\n config.mounts.append(.share(source: directory.path, destination: \"/mnt\"))\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n let value = String(data: buffer.data, encoding: .utf8)\n guard value == \"hello\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned from file 'hello' != '\\(String(data: buffer.data, encoding: .utf8)!)\")\n\n }\n }\n\n func testNestedVirtualizationEnabled() async throws {\n let id = \"test-nested-virt\"\n\n let bs = try await bootstrap()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/true\"]\n config.virtualization = true\n }\n\n do {\n try await container.create()\n try await container.start()\n } catch {\n if let err = error as? ContainerizationError {\n if err.code == .unsupported {\n throw SkipTest(reason: err.message)\n }\n }\n }\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n }\n\n func testContainerManagerCreate() async throws {\n let id = \"test-container-manager\"\n\n // Get the kernel from bootstrap\n let bs = try await bootstrap()\n\n // Create ContainerManager with kernel and initfs reference\n let manager = try ContainerManager(vmm: bs.vmm)\n defer {\n try? manager.delete(id)\n }\n\n let buffer = BufferWriter()\n let container = try await manager.create(\n id,\n image: bs.image,\n rootfs: bs.rootfs\n ) { config in\n config.process.arguments = [\"/bin/echo\", \"ContainerManager test\"]\n config.process.stdout = buffer\n }\n\n // Start the container\n try await container.create()\n try await container.start()\n\n // Wait for completion\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n let output = String(data: buffer.data, encoding: .utf8)\n guard output == \"ContainerManager test\\n\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned 'ContainerManager test' != '\\(output ?? \"nil\")'\")\n }\n }\n\n private func createMountDirectory() throws -> URL {\n let dir = FileManager.default.uniqueTemporaryDirectory(create: true)\n try \"hello\".write(to: dir.appendingPathComponent(\"hi.txt\"), atomically: true, encoding: .utf8)\n return dir\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Mount/Mount.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n#if canImport(Musl)\nimport Musl\nprivate let _mount = Musl.mount\nprivate let _umount = Musl.umount2\n#elseif canImport(Glibc)\nimport Glibc\nprivate let _mount = Glibc.mount\nprivate let _umount = Glibc.umount2\n#endif\n\n// Mount package modeled closely from containerd's: https://github.com/containerd/containerd/tree/main/core/mount\n\n/// `Mount` models a Linux mount (although potentially could be used on other unix platforms), and\n/// provides a simple interface to mount what the type describes.\npublic struct Mount: Sendable {\n // Type specifies the host-specific of the mount.\n public var type: String\n // Source specifies where to mount from. Depending on the host system, this\n // can be a source path or device.\n public var source: String\n // Target specifies an optional subdirectory as a mountpoint.\n public var target: String\n // Options contains zero or more fstab-style mount options.\n public var options: [String]\n\n public init(type: String, source: String, target: String, options: [String]) {\n self.type = type\n self.source = source\n self.target = target\n self.options = options\n }\n}\n\nextension Mount {\n internal struct FlagBehavior {\n let clear: Bool\n let flag: Int32\n\n public init(_ clear: Bool, _ flag: Int32) {\n self.clear = clear\n self.flag = flag\n }\n }\n\n #if os(Linux)\n internal static let flagsDictionary: [String: FlagBehavior] = [\n \"async\": .init(true, MS_SYNCHRONOUS),\n \"atime\": .init(true, MS_NOATIME),\n \"bind\": .init(false, MS_BIND),\n \"defaults\": .init(false, 0),\n \"dev\": .init(true, MS_NODEV),\n \"diratime\": .init(true, MS_NODIRATIME),\n \"dirsync\": .init(false, MS_DIRSYNC),\n \"exec\": .init(true, MS_NOEXEC),\n \"mand\": .init(false, MS_MANDLOCK),\n \"noatime\": .init(false, MS_NOATIME),\n \"nodev\": .init(false, MS_NODEV),\n \"nodiratime\": .init(false, MS_NODIRATIME),\n \"noexec\": .init(false, MS_NOEXEC),\n \"nomand\": .init(true, MS_MANDLOCK),\n \"norelatime\": .init(true, MS_RELATIME),\n \"nostrictatime\": .init(true, MS_STRICTATIME),\n \"nosuid\": .init(false, MS_NOSUID),\n \"rbind\": .init(false, MS_BIND | MS_REC),\n \"relatime\": .init(false, MS_RELATIME),\n \"remount\": .init(false, MS_REMOUNT),\n \"ro\": .init(false, MS_RDONLY),\n \"rw\": .init(true, MS_RDONLY),\n \"strictatime\": .init(false, MS_STRICTATIME),\n \"suid\": .init(true, MS_NOSUID),\n \"sync\": .init(false, MS_SYNCHRONOUS),\n ]\n\n internal struct MountOptions {\n var flags: Int32\n var data: [String]\n\n public init(_ flags: Int32 = 0, data: [String] = []) {\n self.flags = flags\n self.data = data\n }\n }\n\n /// Whether the mount is read only.\n public var readOnly: Bool {\n for option in self.options {\n if option == \"ro\" {\n return true\n }\n }\n return false\n }\n\n /// Mount the mount relative to `root` with the current set of data in the object.\n /// Optionally provide `createWithPerms` to set the permissions for the directory that\n /// it will be mounted at.\n public func mount(root: String, createWithPerms: Int16? = nil) throws {\n var rootURL = URL(fileURLWithPath: root)\n rootURL = rootURL.resolvingSymlinksInPath()\n rootURL = rootURL.appendingPathComponent(self.target)\n try self.mountToTarget(target: rootURL.path, createWithPerms: createWithPerms)\n }\n\n /// Mount the mount with the current set of data in the object. Optionally\n /// provide `createWithPerms` to set the permissions for the directory that\n /// it will be mounted at.\n public func mount(createWithPerms: Int16? = nil) throws {\n try self.mountToTarget(target: self.target, createWithPerms: createWithPerms)\n }\n\n private func mountToTarget(target: String, createWithPerms: Int16?) throws {\n let pageSize = sysconf(_SC_PAGESIZE)\n\n let opts = parseMountOptions()\n let dataString = opts.data.joined(separator: \",\")\n if dataString.count > pageSize {\n throw Error.validation(\"data string exceeds page size (\\(dataString.count) > \\(pageSize))\")\n }\n\n let propagationTypes: Int32 = MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE\n\n // Ensure propagation type change flags aren't included in other calls.\n let originalFlags = opts.flags & ~(propagationTypes)\n\n let targetURL = URL(fileURLWithPath: self.target)\n let targetParent = targetURL.deletingLastPathComponent().path\n if let perms = createWithPerms {\n try mkdirAll(targetParent, perms)\n }\n try mkdirAll(target, 0o755)\n\n if opts.flags & MS_REMOUNT == 0 || !dataString.isEmpty {\n guard _mount(self.source, target, self.type, UInt(originalFlags), dataString) == 0 else {\n throw Error.errno(\n errno,\n \"failed initial mount source=\\(self.source) target=\\(target) type=\\(self.type) data=\\(dataString)\"\n )\n }\n }\n\n if opts.flags & propagationTypes != 0 {\n // Change the propagation type.\n let pflags = propagationTypes | MS_REC | MS_SILENT\n guard _mount(\"\", target, \"\", UInt(opts.flags & pflags), \"\") == 0 else {\n throw Error.errno(errno, \"failed propagation change mount\")\n }\n }\n\n let bindReadOnlyFlags = MS_BIND | MS_RDONLY\n if originalFlags & bindReadOnlyFlags == bindReadOnlyFlags {\n guard _mount(\"\", target, \"\", UInt(originalFlags | MS_REMOUNT), \"\") == 0 else {\n throw Error.errno(errno, \"failed bind mount\")\n }\n }\n }\n\n private func mkdirAll(_ name: String, _ perm: Int16) throws {\n try FileManager.default.createDirectory(\n atPath: name,\n withIntermediateDirectories: true,\n attributes: [.posixPermissions: perm]\n )\n }\n\n private func parseMountOptions() -> MountOptions {\n var mountOpts = MountOptions()\n for option in self.options {\n if let entry = Self.flagsDictionary[option], entry.flag != 0 {\n if entry.clear {\n mountOpts.flags &= ~entry.flag\n } else {\n mountOpts.flags |= entry.flag\n }\n } else {\n mountOpts.data.append(option)\n }\n }\n return mountOpts\n }\n\n /// `Mount` errors\n public enum Error: Swift.Error, CustomStringConvertible {\n case errno(Int32, String)\n case validation(String)\n\n public var description: String {\n switch self {\n case .errno(let errno, let message):\n return \"mount failed with errno \\(errno): \\(message)\"\n case .validation(let message):\n return \"failed during validation: \\(message)\"\n }\n }\n }\n #endif\n}\n"], ["/containerization/Sources/ContainerizationIO/ReadStream.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport NIO\n\n/// `ReadStream` is a utility type for streaming data from a `URL`\n/// or `Data` blob.\npublic class ReadStream {\n public static let bufferSize = Int(1.mib())\n\n private var _stream: InputStream\n private let _buffSize: Int\n private let _data: Data?\n private let _url: URL?\n\n public init() {\n _stream = InputStream(data: .init())\n _buffSize = Self.bufferSize\n self._data = Data()\n self._url = nil\n }\n\n public init(url: URL, bufferSize: Int = bufferSize) throws {\n guard FileManager.default.fileExists(atPath: url.path) else {\n throw Error.noSuchFileOrDirectory(url)\n }\n guard let stream = InputStream(url: url) else {\n throw Error.failedToCreateStream\n }\n self._stream = stream\n self._buffSize = bufferSize\n self._url = url\n self._data = nil\n }\n\n public init(data: Data, bufferSize: Int = bufferSize) {\n self._stream = InputStream(data: data)\n self._buffSize = bufferSize\n self._url = nil\n self._data = data\n }\n\n /// Resets the read stream. This either reassigns\n /// the data buffer or url to a new InputStream internally.\n public func reset() throws {\n self._stream.close()\n if let url = self._url {\n guard let s = InputStream(url: url) else {\n throw Error.failedToCreateStream\n }\n self._stream = s\n return\n }\n let data = self._data ?? Data()\n self._stream = InputStream(data: data)\n }\n\n /// Get access to an `AsyncStream` of `ByteBuffer`'s from the input source.\n public var stream: AsyncStream {\n AsyncStream { cont in\n self._stream.open()\n defer { self._stream.close() }\n\n let readBuffer = UnsafeMutablePointer.allocate(capacity: _buffSize)\n\n while true {\n let byteRead = self._stream.read(readBuffer, maxLength: _buffSize)\n if byteRead <= 0 {\n readBuffer.deallocate()\n cont.finish()\n break\n } else {\n let data = Data(bytes: readBuffer, count: byteRead)\n let buffer = ByteBuffer(bytes: data)\n cont.yield(buffer)\n }\n }\n }\n }\n\n /// Get access to an `AsyncStream` of `Data` objects from the input source.\n public var dataStream: AsyncStream {\n AsyncStream { cont in\n self._stream.open()\n defer { self._stream.close() }\n\n let readBuffer = UnsafeMutablePointer.allocate(capacity: self._buffSize)\n while true {\n let byteRead = self._stream.read(readBuffer, maxLength: self._buffSize)\n if byteRead <= 0 {\n readBuffer.deallocate()\n cont.finish()\n break\n } else {\n let data = Data(bytes: readBuffer, count: byteRead)\n cont.yield(data)\n }\n }\n }\n }\n}\n\nextension ReadStream {\n /// Errors that can be encountered while using a `ReadStream`.\n public enum Error: Swift.Error, CustomStringConvertible {\n case failedToCreateStream\n case noSuchFileOrDirectory(_ p: URL)\n\n public var description: String {\n switch self {\n case .failedToCreateStream:\n return \"failed to create stream\"\n case .noSuchFileOrDirectory(let p):\n return \"no such file or directory: \\(p.path)\"\n }\n }\n }\n}\n"], ["/containerization/Sources/Containerization/SandboxContext/SandboxContext.pb.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// DO NOT EDIT.\n// swift-format-ignore-file\n// swiftlint:disable all\n//\n// Generated by the Swift generator plugin for the protocol buffer compiler.\n// Source: SandboxContext.proto\n//\n// For information on using the generated types, please see the documentation:\n// https://github.com/apple/swift-protobuf/\n\nimport Foundation\nimport SwiftProtobuf\n\n// If the compiler emits an error on this type, it is because this file\n// was generated by a version of the `protoc` Swift plug-in that is\n// incompatible with the version of SwiftProtobuf to which you are linking.\n// Please ensure that you are building against the same version of the API\n// that was used to generate this file.\nfileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {\n struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}\n typealias Version = _2\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_Stdio: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var stdinPort: Int32 {\n get {return _stdinPort ?? 0}\n set {_stdinPort = newValue}\n }\n /// Returns true if `stdinPort` has been explicitly set.\n public var hasStdinPort: Bool {return self._stdinPort != nil}\n /// Clears the value of `stdinPort`. Subsequent reads from it will return its default value.\n public mutating func clearStdinPort() {self._stdinPort = nil}\n\n public var stdoutPort: Int32 {\n get {return _stdoutPort ?? 0}\n set {_stdoutPort = newValue}\n }\n /// Returns true if `stdoutPort` has been explicitly set.\n public var hasStdoutPort: Bool {return self._stdoutPort != nil}\n /// Clears the value of `stdoutPort`. Subsequent reads from it will return its default value.\n public mutating func clearStdoutPort() {self._stdoutPort = nil}\n\n public var stderrPort: Int32 {\n get {return _stderrPort ?? 0}\n set {_stderrPort = newValue}\n }\n /// Returns true if `stderrPort` has been explicitly set.\n public var hasStderrPort: Bool {return self._stderrPort != nil}\n /// Clears the value of `stderrPort`. Subsequent reads from it will return its default value.\n public mutating func clearStderrPort() {self._stderrPort = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _stdinPort: Int32? = nil\n fileprivate var _stdoutPort: Int32? = nil\n fileprivate var _stderrPort: Int32? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var binaryPath: String = String()\n\n public var name: String = String()\n\n public var type: String = String()\n\n public var offset: String = String()\n\n public var magic: String = String()\n\n public var mask: String = String()\n\n public var flags: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetTimeRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var sec: Int64 = 0\n\n public var usec: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetTimeResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SysctlRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var settings: Dictionary = [:]\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SysctlResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var vsockPort: UInt32 = 0\n\n public var guestPath: String = String()\n\n public var guestSocketPermissions: UInt32 {\n get {return _guestSocketPermissions ?? 0}\n set {_guestSocketPermissions = newValue}\n }\n /// Returns true if `guestSocketPermissions` has been explicitly set.\n public var hasGuestSocketPermissions: Bool {return self._guestSocketPermissions != nil}\n /// Clears the value of `guestSocketPermissions`. Subsequent reads from it will return its default value.\n public mutating func clearGuestSocketPermissions() {self._guestSocketPermissions = nil}\n\n public var action: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest.Action = .into\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public enum Action: SwiftProtobuf.Enum, Swift.CaseIterable {\n public typealias RawValue = Int\n case into // = 0\n case outOf // = 1\n case UNRECOGNIZED(Int)\n\n public init() {\n self = .into\n }\n\n public init?(rawValue: Int) {\n switch rawValue {\n case 0: self = .into\n case 1: self = .outOf\n default: self = .UNRECOGNIZED(rawValue)\n }\n }\n\n public var rawValue: Int {\n switch self {\n case .into: return 0\n case .outOf: return 1\n case .UNRECOGNIZED(let i): return i\n }\n }\n\n // The compiler won't synthesize support with the UNRECOGNIZED case.\n public static let allCases: [Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest.Action] = [\n .into,\n .outOf,\n ]\n\n }\n\n public init() {}\n\n fileprivate var _guestSocketPermissions: UInt32? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_MountRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var type: String = String()\n\n public var source: String = String()\n\n public var destination: String = String()\n\n public var options: [String] = []\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_MountResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_UmountRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var path: String = String()\n\n public var flags: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_UmountResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetenvRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var key: String = String()\n\n public var value: String {\n get {return _value ?? String()}\n set {_value = newValue}\n }\n /// Returns true if `value` has been explicitly set.\n public var hasValue: Bool {return self._value != nil}\n /// Clears the value of `value`. Subsequent reads from it will return its default value.\n public mutating func clearValue() {self._value = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _value: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetenvResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_GetenvRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var key: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_GetenvResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var value: String {\n get {return _value ?? String()}\n set {_value = newValue}\n }\n /// Returns true if `value` has been explicitly set.\n public var hasValue: Bool {return self._value != nil}\n /// Clears the value of `value`. Subsequent reads from it will return its default value.\n public mutating func clearValue() {self._value = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _value: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var stdin: UInt32 {\n get {return _stdin ?? 0}\n set {_stdin = newValue}\n }\n /// Returns true if `stdin` has been explicitly set.\n public var hasStdin: Bool {return self._stdin != nil}\n /// Clears the value of `stdin`. Subsequent reads from it will return its default value.\n public mutating func clearStdin() {self._stdin = nil}\n\n public var stdout: UInt32 {\n get {return _stdout ?? 0}\n set {_stdout = newValue}\n }\n /// Returns true if `stdout` has been explicitly set.\n public var hasStdout: Bool {return self._stdout != nil}\n /// Clears the value of `stdout`. Subsequent reads from it will return its default value.\n public mutating func clearStdout() {self._stdout = nil}\n\n public var stderr: UInt32 {\n get {return _stderr ?? 0}\n set {_stderr = newValue}\n }\n /// Returns true if `stderr` has been explicitly set.\n public var hasStderr: Bool {return self._stderr != nil}\n /// Clears the value of `stderr`. Subsequent reads from it will return its default value.\n public mutating func clearStderr() {self._stderr = nil}\n\n public var configuration: Data = Data()\n\n public var options: Data {\n get {return _options ?? Data()}\n set {_options = newValue}\n }\n /// Returns true if `options` has been explicitly set.\n public var hasOptions: Bool {return self._options != nil}\n /// Clears the value of `options`. Subsequent reads from it will return its default value.\n public mutating func clearOptions() {self._options = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n fileprivate var _stdin: UInt32? = nil\n fileprivate var _stdout: UInt32? = nil\n fileprivate var _stderr: UInt32? = nil\n fileprivate var _options: Data? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var exitCode: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var rows: UInt32 = 0\n\n public var columns: UInt32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_StartProcessRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_StartProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var pid: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_KillProcessRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var signal: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_KillProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var result: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_MkdirRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var path: String = String()\n\n public var all: Bool = false\n\n public var perms: UInt32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_MkdirResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var interface: String = String()\n\n public var up: Bool = false\n\n public var mtu: UInt32 {\n get {return _mtu ?? 0}\n set {_mtu = newValue}\n }\n /// Returns true if `mtu` has been explicitly set.\n public var hasMtu: Bool {return self._mtu != nil}\n /// Clears the value of `mtu`. Subsequent reads from it will return its default value.\n public mutating func clearMtu() {self._mtu = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _mtu: UInt32? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var interface: String = String()\n\n public var address: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var interface: String = String()\n\n public var address: String = String()\n\n public var srcAddr: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var interface: String = String()\n\n public var gateway: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var location: String = String()\n\n public var nameservers: [String] = []\n\n public var domain: String {\n get {return _domain ?? String()}\n set {_domain = newValue}\n }\n /// Returns true if `domain` has been explicitly set.\n public var hasDomain: Bool {return self._domain != nil}\n /// Clears the value of `domain`. Subsequent reads from it will return its default value.\n public mutating func clearDomain() {self._domain = nil}\n\n public var searchDomains: [String] = []\n\n public var options: [String] = []\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _domain: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var location: String = String()\n\n public var entries: [Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.HostsEntry] = []\n\n public var comment: String {\n get {return _comment ?? String()}\n set {_comment = newValue}\n }\n /// Returns true if `comment` has been explicitly set.\n public var hasComment: Bool {return self._comment != nil}\n /// Clears the value of `comment`. Subsequent reads from it will return its default value.\n public mutating func clearComment() {self._comment = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public struct HostsEntry: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var ipAddress: String = String()\n\n public var hostnames: [String] = []\n\n public var comment: String {\n get {return _comment ?? String()}\n set {_comment = newValue}\n }\n /// Returns true if `comment` has been explicitly set.\n public var hasComment: Bool {return self._comment != nil}\n /// Clears the value of `comment`. Subsequent reads from it will return its default value.\n public mutating func clearComment() {self._comment = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _comment: String? = nil\n }\n\n public init() {}\n\n fileprivate var _comment: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SyncRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SyncResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_KillRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var pid: Int32 = 0\n\n public var signal: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_KillResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var result: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\n// MARK: - Code below here is support for the SwiftProtobuf runtime.\n\nfileprivate let _protobuf_package = \"com.apple.containerization.sandbox.v3\"\n\nextension Com_Apple_Containerization_Sandbox_V3_Stdio: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Stdio\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"stdinPort\"),\n 2: .same(proto: \"stdoutPort\"),\n 3: .same(proto: \"stderrPort\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self._stdinPort) }()\n case 2: try { try decoder.decodeSingularInt32Field(value: &self._stdoutPort) }()\n case 3: try { try decoder.decodeSingularInt32Field(value: &self._stderrPort) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n try { if let v = self._stdinPort {\n try visitor.visitSingularInt32Field(value: v, fieldNumber: 1)\n } }()\n try { if let v = self._stdoutPort {\n try visitor.visitSingularInt32Field(value: v, fieldNumber: 2)\n } }()\n try { if let v = self._stderrPort {\n try visitor.visitSingularInt32Field(value: v, fieldNumber: 3)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_Stdio, rhs: Com_Apple_Containerization_Sandbox_V3_Stdio) -> Bool {\n if lhs._stdinPort != rhs._stdinPort {return false}\n if lhs._stdoutPort != rhs._stdoutPort {return false}\n if lhs._stderrPort != rhs._stderrPort {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetupEmulatorRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"binary_path\"),\n 2: .same(proto: \"name\"),\n 3: .same(proto: \"type\"),\n 4: .same(proto: \"offset\"),\n 5: .same(proto: \"magic\"),\n 6: .same(proto: \"mask\"),\n 7: .same(proto: \"flags\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.binaryPath) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.name) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.type) }()\n case 4: try { try decoder.decodeSingularStringField(value: &self.offset) }()\n case 5: try { try decoder.decodeSingularStringField(value: &self.magic) }()\n case 6: try { try decoder.decodeSingularStringField(value: &self.mask) }()\n case 7: try { try decoder.decodeSingularStringField(value: &self.flags) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.binaryPath.isEmpty {\n try visitor.visitSingularStringField(value: self.binaryPath, fieldNumber: 1)\n }\n if !self.name.isEmpty {\n try visitor.visitSingularStringField(value: self.name, fieldNumber: 2)\n }\n if !self.type.isEmpty {\n try visitor.visitSingularStringField(value: self.type, fieldNumber: 3)\n }\n if !self.offset.isEmpty {\n try visitor.visitSingularStringField(value: self.offset, fieldNumber: 4)\n }\n if !self.magic.isEmpty {\n try visitor.visitSingularStringField(value: self.magic, fieldNumber: 5)\n }\n if !self.mask.isEmpty {\n try visitor.visitSingularStringField(value: self.mask, fieldNumber: 6)\n }\n if !self.flags.isEmpty {\n try visitor.visitSingularStringField(value: self.flags, fieldNumber: 7)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest, rhs: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest) -> Bool {\n if lhs.binaryPath != rhs.binaryPath {return false}\n if lhs.name != rhs.name {return false}\n if lhs.type != rhs.type {return false}\n if lhs.offset != rhs.offset {return false}\n if lhs.magic != rhs.magic {return false}\n if lhs.mask != rhs.mask {return false}\n if lhs.flags != rhs.flags {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetupEmulatorResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse, rhs: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetTimeRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetTimeRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"sec\"),\n 2: .same(proto: \"usec\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt64Field(value: &self.sec) }()\n case 2: try { try decoder.decodeSingularInt32Field(value: &self.usec) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.sec != 0 {\n try visitor.visitSingularInt64Field(value: self.sec, fieldNumber: 1)\n }\n if self.usec != 0 {\n try visitor.visitSingularInt32Field(value: self.usec, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest, rhs: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest) -> Bool {\n if lhs.sec != rhs.sec {return false}\n if lhs.usec != rhs.usec {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetTimeResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetTimeResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetTimeResponse, rhs: Com_Apple_Containerization_Sandbox_V3_SetTimeResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SysctlRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SysctlRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"settings\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.settings) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.settings.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.settings, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SysctlRequest, rhs: Com_Apple_Containerization_Sandbox_V3_SysctlRequest) -> Bool {\n if lhs.settings != rhs.settings {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SysctlResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SysctlResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SysctlResponse, rhs: Com_Apple_Containerization_Sandbox_V3_SysctlResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ProxyVsockRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .standard(proto: \"vsock_port\"),\n 3: .same(proto: \"guestPath\"),\n 4: .same(proto: \"guestSocketPermissions\"),\n 5: .same(proto: \"action\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularUInt32Field(value: &self.vsockPort) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.guestPath) }()\n case 4: try { try decoder.decodeSingularUInt32Field(value: &self._guestSocketPermissions) }()\n case 5: try { try decoder.decodeSingularEnumField(value: &self.action) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n if self.vsockPort != 0 {\n try visitor.visitSingularUInt32Field(value: self.vsockPort, fieldNumber: 2)\n }\n if !self.guestPath.isEmpty {\n try visitor.visitSingularStringField(value: self.guestPath, fieldNumber: 3)\n }\n try { if let v = self._guestSocketPermissions {\n try visitor.visitSingularUInt32Field(value: v, fieldNumber: 4)\n } }()\n if self.action != .into {\n try visitor.visitSingularEnumField(value: self.action, fieldNumber: 5)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest, rhs: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.vsockPort != rhs.vsockPort {return false}\n if lhs.guestPath != rhs.guestPath {return false}\n if lhs._guestSocketPermissions != rhs._guestSocketPermissions {return false}\n if lhs.action != rhs.action {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest.Action: SwiftProtobuf._ProtoNameProviding {\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 0: .same(proto: \"INTO\"),\n 1: .same(proto: \"OUT_OF\"),\n ]\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ProxyVsockResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse, rhs: Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".StopVsockProxyRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest, rhs: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".StopVsockProxyResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse, rhs: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_MountRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".MountRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"type\"),\n 2: .same(proto: \"source\"),\n 3: .same(proto: \"destination\"),\n 4: .same(proto: \"options\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.type) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.source) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.destination) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.options) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.type.isEmpty {\n try visitor.visitSingularStringField(value: self.type, fieldNumber: 1)\n }\n if !self.source.isEmpty {\n try visitor.visitSingularStringField(value: self.source, fieldNumber: 2)\n }\n if !self.destination.isEmpty {\n try visitor.visitSingularStringField(value: self.destination, fieldNumber: 3)\n }\n if !self.options.isEmpty {\n try visitor.visitRepeatedStringField(value: self.options, fieldNumber: 4)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_MountRequest, rhs: Com_Apple_Containerization_Sandbox_V3_MountRequest) -> Bool {\n if lhs.type != rhs.type {return false}\n if lhs.source != rhs.source {return false}\n if lhs.destination != rhs.destination {return false}\n if lhs.options != rhs.options {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_MountResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".MountResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_MountResponse, rhs: Com_Apple_Containerization_Sandbox_V3_MountResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_UmountRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".UmountRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"path\"),\n 2: .same(proto: \"flags\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.path) }()\n case 2: try { try decoder.decodeSingularInt32Field(value: &self.flags) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.path.isEmpty {\n try visitor.visitSingularStringField(value: self.path, fieldNumber: 1)\n }\n if self.flags != 0 {\n try visitor.visitSingularInt32Field(value: self.flags, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_UmountRequest, rhs: Com_Apple_Containerization_Sandbox_V3_UmountRequest) -> Bool {\n if lhs.path != rhs.path {return false}\n if lhs.flags != rhs.flags {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_UmountResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".UmountResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_UmountResponse, rhs: Com_Apple_Containerization_Sandbox_V3_UmountResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetenvRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetenvRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"key\"),\n 2: .same(proto: \"value\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.key) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._value) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.key.isEmpty {\n try visitor.visitSingularStringField(value: self.key, fieldNumber: 1)\n }\n try { if let v = self._value {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetenvRequest, rhs: Com_Apple_Containerization_Sandbox_V3_SetenvRequest) -> Bool {\n if lhs.key != rhs.key {return false}\n if lhs._value != rhs._value {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetenvResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetenvResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetenvResponse, rhs: Com_Apple_Containerization_Sandbox_V3_SetenvResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_GetenvRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".GetenvRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"key\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.key) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.key.isEmpty {\n try visitor.visitSingularStringField(value: self.key, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_GetenvRequest, rhs: Com_Apple_Containerization_Sandbox_V3_GetenvRequest) -> Bool {\n if lhs.key != rhs.key {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_GetenvResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".GetenvResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"value\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self._value) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n try { if let v = self._value {\n try visitor.visitSingularStringField(value: v, fieldNumber: 1)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_GetenvResponse, rhs: Com_Apple_Containerization_Sandbox_V3_GetenvResponse) -> Bool {\n if lhs._value != rhs._value {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CreateProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n 3: .same(proto: \"stdin\"),\n 4: .same(proto: \"stdout\"),\n 5: .same(proto: \"stderr\"),\n 6: .same(proto: \"configuration\"),\n 7: .same(proto: \"options\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n case 3: try { try decoder.decodeSingularUInt32Field(value: &self._stdin) }()\n case 4: try { try decoder.decodeSingularUInt32Field(value: &self._stdout) }()\n case 5: try { try decoder.decodeSingularUInt32Field(value: &self._stderr) }()\n case 6: try { try decoder.decodeSingularBytesField(value: &self.configuration) }()\n case 7: try { try decoder.decodeSingularBytesField(value: &self._options) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try { if let v = self._stdin {\n try visitor.visitSingularUInt32Field(value: v, fieldNumber: 3)\n } }()\n try { if let v = self._stdout {\n try visitor.visitSingularUInt32Field(value: v, fieldNumber: 4)\n } }()\n try { if let v = self._stderr {\n try visitor.visitSingularUInt32Field(value: v, fieldNumber: 5)\n } }()\n if !self.configuration.isEmpty {\n try visitor.visitSingularBytesField(value: self.configuration, fieldNumber: 6)\n }\n try { if let v = self._options {\n try visitor.visitSingularBytesField(value: v, fieldNumber: 7)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs._stdin != rhs._stdin {return false}\n if lhs._stdout != rhs._stdout {return false}\n if lhs._stderr != rhs._stderr {return false}\n if lhs.configuration != rhs.configuration {return false}\n if lhs._options != rhs._options {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CreateProcessResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".WaitProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".WaitProcessResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"exitCode\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.exitCode) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.exitCode != 0 {\n try visitor.visitSingularInt32Field(value: self.exitCode, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse) -> Bool {\n if lhs.exitCode != rhs.exitCode {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ResizeProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n 3: .same(proto: \"rows\"),\n 4: .same(proto: \"columns\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n case 3: try { try decoder.decodeSingularUInt32Field(value: &self.rows) }()\n case 4: try { try decoder.decodeSingularUInt32Field(value: &self.columns) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n if self.rows != 0 {\n try visitor.visitSingularUInt32Field(value: self.rows, fieldNumber: 3)\n }\n if self.columns != 0 {\n try visitor.visitSingularUInt32Field(value: self.columns, fieldNumber: 4)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.rows != rhs.rows {return false}\n if lhs.columns != rhs.columns {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ResizeProcessResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".DeleteProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".DeleteProcessResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_StartProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".StartProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_StartProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".StartProcessResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"pid\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.pid) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.pid != 0 {\n try visitor.visitSingularInt32Field(value: self.pid, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_StartProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_StartProcessResponse) -> Bool {\n if lhs.pid != rhs.pid {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_KillProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".KillProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n 3: .same(proto: \"signal\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n case 3: try { try decoder.decodeSingularInt32Field(value: &self.signal) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n if self.signal != 0 {\n try visitor.visitSingularInt32Field(value: self.signal, fieldNumber: 3)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.signal != rhs.signal {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_KillProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".KillProcessResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"result\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.result) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.result != 0 {\n try visitor.visitSingularInt32Field(value: self.result, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_KillProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_KillProcessResponse) -> Bool {\n if lhs.result != rhs.result {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CloseProcessStdinRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest, rhs: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CloseProcessStdinResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse, rhs: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_MkdirRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".MkdirRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"path\"),\n 2: .same(proto: \"all\"),\n 3: .same(proto: \"perms\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.path) }()\n case 2: try { try decoder.decodeSingularBoolField(value: &self.all) }()\n case 3: try { try decoder.decodeSingularUInt32Field(value: &self.perms) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.path.isEmpty {\n try visitor.visitSingularStringField(value: self.path, fieldNumber: 1)\n }\n if self.all != false {\n try visitor.visitSingularBoolField(value: self.all, fieldNumber: 2)\n }\n if self.perms != 0 {\n try visitor.visitSingularUInt32Field(value: self.perms, fieldNumber: 3)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_MkdirRequest, rhs: Com_Apple_Containerization_Sandbox_V3_MkdirRequest) -> Bool {\n if lhs.path != rhs.path {return false}\n if lhs.all != rhs.all {return false}\n if lhs.perms != rhs.perms {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_MkdirResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".MkdirResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_MkdirResponse, rhs: Com_Apple_Containerization_Sandbox_V3_MkdirResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpLinkSetRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"interface\"),\n 2: .same(proto: \"up\"),\n 3: .same(proto: \"mtu\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.interface) }()\n case 2: try { try decoder.decodeSingularBoolField(value: &self.up) }()\n case 3: try { try decoder.decodeSingularUInt32Field(value: &self._mtu) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.interface.isEmpty {\n try visitor.visitSingularStringField(value: self.interface, fieldNumber: 1)\n }\n if self.up != false {\n try visitor.visitSingularBoolField(value: self.up, fieldNumber: 2)\n }\n try { if let v = self._mtu {\n try visitor.visitSingularUInt32Field(value: v, fieldNumber: 3)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest, rhs: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest) -> Bool {\n if lhs.interface != rhs.interface {return false}\n if lhs.up != rhs.up {return false}\n if lhs._mtu != rhs._mtu {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpLinkSetResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse, rhs: Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpAddrAddRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"interface\"),\n 2: .same(proto: \"address\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.interface) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.address) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.interface.isEmpty {\n try visitor.visitSingularStringField(value: self.interface, fieldNumber: 1)\n }\n if !self.address.isEmpty {\n try visitor.visitSingularStringField(value: self.address, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest, rhs: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest) -> Bool {\n if lhs.interface != rhs.interface {return false}\n if lhs.address != rhs.address {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpAddrAddResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse, rhs: Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpRouteAddLinkRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"interface\"),\n 2: .same(proto: \"address\"),\n 3: .same(proto: \"srcAddr\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.interface) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.address) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.srcAddr) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.interface.isEmpty {\n try visitor.visitSingularStringField(value: self.interface, fieldNumber: 1)\n }\n if !self.address.isEmpty {\n try visitor.visitSingularStringField(value: self.address, fieldNumber: 2)\n }\n if !self.srcAddr.isEmpty {\n try visitor.visitSingularStringField(value: self.srcAddr, fieldNumber: 3)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest, rhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest) -> Bool {\n if lhs.interface != rhs.interface {return false}\n if lhs.address != rhs.address {return false}\n if lhs.srcAddr != rhs.srcAddr {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpRouteAddLinkResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse, rhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpRouteAddDefaultRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"interface\"),\n 2: .same(proto: \"gateway\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.interface) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.gateway) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.interface.isEmpty {\n try visitor.visitSingularStringField(value: self.interface, fieldNumber: 1)\n }\n if !self.gateway.isEmpty {\n try visitor.visitSingularStringField(value: self.gateway, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest, rhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest) -> Bool {\n if lhs.interface != rhs.interface {return false}\n if lhs.gateway != rhs.gateway {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpRouteAddDefaultResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse, rhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ConfigureDnsRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"location\"),\n 2: .same(proto: \"nameservers\"),\n 3: .same(proto: \"domain\"),\n 4: .same(proto: \"searchDomains\"),\n 5: .same(proto: \"options\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.location) }()\n case 2: try { try decoder.decodeRepeatedStringField(value: &self.nameservers) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self._domain) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.searchDomains) }()\n case 5: try { try decoder.decodeRepeatedStringField(value: &self.options) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.location.isEmpty {\n try visitor.visitSingularStringField(value: self.location, fieldNumber: 1)\n }\n if !self.nameservers.isEmpty {\n try visitor.visitRepeatedStringField(value: self.nameservers, fieldNumber: 2)\n }\n try { if let v = self._domain {\n try visitor.visitSingularStringField(value: v, fieldNumber: 3)\n } }()\n if !self.searchDomains.isEmpty {\n try visitor.visitRepeatedStringField(value: self.searchDomains, fieldNumber: 4)\n }\n if !self.options.isEmpty {\n try visitor.visitRepeatedStringField(value: self.options, fieldNumber: 5)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest, rhs: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest) -> Bool {\n if lhs.location != rhs.location {return false}\n if lhs.nameservers != rhs.nameservers {return false}\n if lhs._domain != rhs._domain {return false}\n if lhs.searchDomains != rhs.searchDomains {return false}\n if lhs.options != rhs.options {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ConfigureDnsResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse, rhs: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ConfigureHostsRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"location\"),\n 2: .same(proto: \"entries\"),\n 3: .same(proto: \"comment\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.location) }()\n case 2: try { try decoder.decodeRepeatedMessageField(value: &self.entries) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self._comment) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.location.isEmpty {\n try visitor.visitSingularStringField(value: self.location, fieldNumber: 1)\n }\n if !self.entries.isEmpty {\n try visitor.visitRepeatedMessageField(value: self.entries, fieldNumber: 2)\n }\n try { if let v = self._comment {\n try visitor.visitSingularStringField(value: v, fieldNumber: 3)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest, rhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest) -> Bool {\n if lhs.location != rhs.location {return false}\n if lhs.entries != rhs.entries {return false}\n if lhs._comment != rhs._comment {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.HostsEntry: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.protoMessageName + \".HostsEntry\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"ipAddress\"),\n 2: .same(proto: \"hostnames\"),\n 3: .same(proto: \"comment\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.ipAddress) }()\n case 2: try { try decoder.decodeRepeatedStringField(value: &self.hostnames) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self._comment) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.ipAddress.isEmpty {\n try visitor.visitSingularStringField(value: self.ipAddress, fieldNumber: 1)\n }\n if !self.hostnames.isEmpty {\n try visitor.visitRepeatedStringField(value: self.hostnames, fieldNumber: 2)\n }\n try { if let v = self._comment {\n try visitor.visitSingularStringField(value: v, fieldNumber: 3)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.HostsEntry, rhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.HostsEntry) -> Bool {\n if lhs.ipAddress != rhs.ipAddress {return false}\n if lhs.hostnames != rhs.hostnames {return false}\n if lhs._comment != rhs._comment {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ConfigureHostsResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse, rhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SyncRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SyncRequest\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SyncRequest, rhs: Com_Apple_Containerization_Sandbox_V3_SyncRequest) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SyncResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SyncResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SyncResponse, rhs: Com_Apple_Containerization_Sandbox_V3_SyncResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_KillRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".KillRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"pid\"),\n 3: .same(proto: \"signal\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.pid) }()\n case 3: try { try decoder.decodeSingularInt32Field(value: &self.signal) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.pid != 0 {\n try visitor.visitSingularInt32Field(value: self.pid, fieldNumber: 1)\n }\n if self.signal != 0 {\n try visitor.visitSingularInt32Field(value: self.signal, fieldNumber: 3)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_KillRequest, rhs: Com_Apple_Containerization_Sandbox_V3_KillRequest) -> Bool {\n if lhs.pid != rhs.pid {return false}\n if lhs.signal != rhs.signal {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_KillResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".KillResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"result\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.result) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.result != 0 {\n try visitor.visitSingularInt32Field(value: self.result, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_KillResponse, rhs: Com_Apple_Containerization_Sandbox_V3_KillResponse) -> Bool {\n if lhs.result != rhs.result {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n"], ["/containerization/Sources/Containerization/Image/ImageStore/ImageStore+OCILayout.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\nextension ImageStore {\n /// Exports the specified images and their associated layers to an OCI Image Layout directory.\n /// This function saves the images identified by the `references` array, including their\n /// manifests and layer blobs, into a directory structure compliant with the OCI Image Layout specification at the given `out` URL.\n ///\n /// - Parameters:\n /// - references: A list image references that exists in the `ImageStore` that are to be saved in the OCI Image Layout format.\n /// - out: A URL to a directory on disk at which the OCI Image Layout structure will be created.\n /// - platform: An optional parameter to indicate the platform to be saved for the images.\n /// Defaults to `nil` signifying that layers for all supported platforms by the images will be saved.\n ///\n public func save(references: [String], out: URL, platform: Platform? = nil) async throws {\n let matcher = createPlatformMatcher(for: platform)\n let fileManager = FileManager.default\n let tempDir = fileManager.uniqueTemporaryDirectory()\n defer {\n try? fileManager.removeItem(at: tempDir)\n }\n\n var toSave: [Image] = []\n for reference in references {\n let image = try await self.get(reference: reference)\n let allowedMediaTypes = [MediaTypes.dockerManifestList, MediaTypes.index]\n guard allowedMediaTypes.contains(image.mediaType) else {\n throw ContainerizationError(.internalError, message: \"Cannot save image \\(image.reference) with Index media type \\(image.mediaType)\")\n }\n toSave.append(image)\n }\n let client = try LocalOCILayoutClient(root: out)\n var saved: [Descriptor] = []\n\n for image in toSave {\n let ref = try Reference.parse(image.reference)\n let name = ref.path\n guard let tag = ref.tag ?? ref.digest else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid tag/digest for image reference \\(image.reference)\")\n }\n let operation = ExportOperation(name: name, tag: tag, contentStore: self.contentStore, client: client, progress: nil)\n var descriptor = try await operation.export(index: image.descriptor, platforms: matcher)\n client.setImageReferenceAnnotation(descriptor: &descriptor, reference: image.reference)\n saved.append(descriptor)\n }\n try client.createOCILayoutStructure(directory: out, manifests: saved)\n }\n\n /// Imports one or more images and their associated layers from an OCI Image Layout directory.\n ///\n /// - Parameters:\n /// - directory: A URL to a directory on disk at that follows the OCI Image Layout structure.\n /// - progress: An optional handler over which progress update events about the load operation can be received.\n /// - Returns: The list of images that were loaded into the `ImageStore`.\n ///\n public func load(from directory: URL, progress: ProgressHandler? = nil) async throws -> [Image] {\n let client = try LocalOCILayoutClient(root: directory)\n let index = try client.loadIndexFromOCILayout(directory: directory)\n let matcher = createPlatformMatcher(for: nil)\n\n var loaded: [Image.Description] = []\n let (id, tempDir) = try await self.contentStore.newIngestSession()\n do {\n for descriptor in index.manifests {\n guard let reference = client.getImageReferencefromDescriptor(descriptor: descriptor) else {\n continue\n }\n let ref = try Reference.parse(reference)\n let name = ref.path\n let operation = ImportOperation(name: name, contentStore: self.contentStore, client: client, ingestDir: tempDir, progress: progress)\n let indexDesc = try await operation.import(root: descriptor, matcher: matcher)\n loaded.append(Image.Description(reference: reference, descriptor: indexDesc))\n }\n\n let loadedImages = loaded\n let importedImages = try await self.lock.withLock { lock in\n var images: [Image] = []\n try await self.contentStore.completeIngestSession(id)\n for description in loadedImages {\n let img = try await self._create(description: description, lock: lock)\n images.append(img)\n }\n return images\n }\n guard importedImages.count > 0 else {\n throw ContainerizationError(.internalError, message: \"Failed to import image\")\n }\n return importedImages\n } catch {\n try? await self.contentStore.cancelIngestSession(id)\n throw error\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/KeychainHelper.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport ContainerizationOS\n\n/// Helper type to lookup registry related values in the macOS keychain.\npublic struct KeychainHelper: Sendable {\n private let id: String\n public init(id: String) {\n self.id = id\n }\n\n /// Lookup authorization data for a given registry domain.\n public func lookup(domain: String) throws -> Authentication {\n let kq = KeychainQuery()\n\n do {\n guard let fetched = try kq.get(id: self.id, host: domain) else {\n throw Self.Error.keyNotFound\n }\n return BasicAuthentication(\n username: fetched.account,\n password: fetched.data\n )\n } catch let err as KeychainQuery.Error {\n switch err {\n case .keyNotPresent(_):\n throw Self.Error.keyNotFound\n default:\n throw Self.Error.queryError(\"query failure: \\(String(describing: err))\")\n }\n }\n }\n\n /// Delete authorization data for a given domain from the keychain.\n public func delete(domain: String) throws {\n let kq = KeychainQuery()\n try kq.delete(id: self.id, host: domain)\n }\n\n /// Save authorization data for a given domain to the keychain.\n public func save(domain: String, username: String, password: String) throws {\n let kq = KeychainQuery()\n try kq.save(id: self.id, host: domain, user: username, token: password)\n }\n\n /// Prompt for authorization data for a given domain to be saved to the keychain.\n /// This will cause the current terminal to enter a password prompt state where\n /// key strokes are hidden.\n public func credentialPrompt(domain: String) throws -> Authentication {\n let username = try userPrompt(domain: domain)\n let password = try passwordPrompt()\n return BasicAuthentication(username: username, password: password)\n }\n\n /// Prompts the current stdin for a username entry and then returns the value.\n public func userPrompt(domain: String) throws -> String {\n print(\"Provide registry username \\(domain): \", terminator: \"\")\n guard let username = readLine() else {\n throw Self.Error.invalidInput\n }\n return username\n }\n\n /// Prompts the current stdin for a password entry and then returns the value.\n /// This will cause the current stdin (if it is a terminal) to hide keystrokes\n /// by disabling echo.\n public func passwordPrompt() throws -> String {\n print(\"Provide registry password: \", terminator: \"\")\n let console = try Terminal.current\n defer { console.tryReset() }\n try console.disableEcho()\n\n guard let password = readLine() else {\n throw Self.Error.invalidInput\n }\n return password\n }\n}\n\nextension KeychainHelper {\n /// `KeychainHelper` errors.\n public enum Error: Swift.Error {\n case keyNotFound\n case invalidInput\n case queryError(String)\n }\n}\n#endif\n"], ["/containerization/Sources/Containerization/VZVirtualMachineManager.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport Logging\n\n/// A virtualization.framework backed `VirtualMachineManager` implementation.\npublic struct VZVirtualMachineManager: VirtualMachineManager {\n private let kernel: Kernel\n private let bootlog: String?\n private let initialFilesystem: Mount\n private let logger: Logger?\n\n public init(\n kernel: Kernel,\n initialFilesystem: Mount,\n bootlog: String? = nil,\n logger: Logger? = nil\n ) {\n self.kernel = kernel\n self.bootlog = bootlog\n self.initialFilesystem = initialFilesystem\n self.logger = logger\n }\n\n public func create(container: Container) throws -> any VirtualMachineInstance {\n guard let c = container as? LinuxContainer else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"provided container is not a LinuxContainer\"\n )\n }\n\n return try VZVirtualMachineInstance(\n logger: self.logger,\n with: { config in\n config.cpus = container.cpus\n config.memoryInBytes = container.memoryInBytes\n\n config.kernel = self.kernel\n config.initialFilesystem = self.initialFilesystem\n\n config.interfaces = container.interfaces\n if let bootlog {\n config.bootlog = URL(filePath: bootlog)\n }\n config.rosetta = c.config.rosetta\n config.nestedVirtualization = c.config.virtualization\n\n config.mounts = [c.rootfs] + c.config.mounts\n })\n }\n}\n#endif\n"], ["/containerization/vminitd/Sources/vminitd/OSFile.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nstruct OSFile: Sendable {\n private let fd: Int32\n\n enum IOAction: Equatable {\n case eof\n case again\n case success\n case brokenPipe\n case error(_ errno: Int32)\n }\n\n var closed: Bool {\n Foundation.fcntl(fd, F_GETFD) == -1 && errno == EBADF\n }\n\n var fileDescriptor: Int32 { fd }\n\n init(fd: Int32) {\n self.fd = fd\n }\n\n init(handle: FileHandle) {\n self.fd = handle.fileDescriptor\n }\n\n func close() throws {\n guard Foundation.close(self.fd) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n }\n\n func read(_ buffer: UnsafeMutableBufferPointer) -> (read: Int, action: IOAction) {\n if buffer.count == 0 {\n return (0, .success)\n }\n\n var bytesRead: Int = 0\n while true {\n let n = Foundation.read(\n self.fd,\n buffer.baseAddress!.advanced(by: bytesRead),\n buffer.count - bytesRead\n )\n if n == -1 {\n if errno == EAGAIN || errno == EIO {\n return (bytesRead, .again)\n }\n return (bytesRead, .error(errno))\n }\n\n if n == 0 {\n return (bytesRead, .eof)\n }\n\n bytesRead += n\n if bytesRead < buffer.count {\n continue\n }\n return (bytesRead, .success)\n }\n }\n\n func write(_ buffer: UnsafeMutableBufferPointer) -> (wrote: Int, action: IOAction) {\n if buffer.count == 0 {\n return (0, .success)\n }\n\n var bytesWrote: Int = 0\n while true {\n let n = Foundation.write(\n self.fd,\n buffer.baseAddress!.advanced(by: bytesWrote),\n buffer.count - bytesWrote\n )\n if n == -1 {\n if errno == EAGAIN || errno == EIO {\n return (bytesWrote, .again)\n }\n return (bytesWrote, .error(errno))\n }\n\n if n == 0 {\n return (bytesWrote, .brokenPipe)\n }\n\n bytesWrote += n\n if bytesWrote < buffer.count {\n continue\n }\n return (bytesWrote, .success)\n }\n }\n\n static func pipe() -> (read: Self, write: Self) {\n let pipe = Pipe()\n return (Self(handle: pipe.fileHandleForReading), Self(handle: pipe.fileHandleForWriting))\n }\n\n static func open(path: String) throws -> Self {\n try open(path: path, mode: O_RDONLY | O_CLOEXEC)\n }\n\n static func open(path: String, mode: Int32) throws -> Self {\n let fd = Foundation.open(path, mode)\n if fd < 0 {\n throw POSIXError(.init(rawValue: errno)!)\n }\n return Self(fd: fd)\n }\n}\n"], ["/containerization/Sources/Containerization/Image/ImageStore/ImageStore+ReferenceManager.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\nextension ImageStore {\n /// A ReferenceManager handles the mappings between an image's\n /// reference and the underlying descriptor inside of a content store.\n internal actor ReferenceManager: Sendable {\n private let path: URL\n\n private typealias State = [String: Descriptor]\n private var images: State\n\n public init(path: URL) throws {\n try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true)\n\n self.path = path\n self.images = [:]\n }\n\n private func load() throws -> State {\n let statePath = self.path.appendingPathComponent(\"state.json\")\n guard FileManager.default.fileExists(atPath: statePath.absolutePath()) else {\n return [:]\n }\n do {\n let data = try Data(contentsOf: statePath)\n return try JSONDecoder().decode(State.self, from: data)\n } catch {\n throw ContainerizationError(.internalError, message: \"Failed to load image state \\(error.localizedDescription)\")\n }\n }\n\n private func save(_ state: State) throws {\n let statePath = self.path.appendingPathComponent(\"state.json\")\n try JSONEncoder().encode(state).write(to: statePath)\n }\n\n public func delete(reference: String) throws {\n var state = try self.load()\n state.removeValue(forKey: reference)\n try self.save(state)\n }\n\n public func delete(image: Image.Description) throws {\n try self.delete(reference: image.reference)\n }\n\n public func create(description: Image.Description) throws {\n var state = try self.load()\n state[description.reference] = description.descriptor\n try self.save(state)\n }\n\n public func list() throws -> [Image.Description] {\n let state = try self.load()\n return state.map { key, val in\n let description = Image.Description(reference: key, descriptor: val)\n return description\n }\n }\n\n public func get(reference: String) throws -> Image.Description {\n let images = try self.list()\n let hit = images.first(where: { image in\n image.reference == reference\n })\n guard let hit else {\n throw ContainerizationError(.notFound, message: \"image \\(reference) not found\")\n }\n return hit\n }\n }\n}\n"], ["/containerization/Sources/Containerization/NATNetworkInterface.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\n\nimport vmnet\nimport Virtualization\nimport ContainerizationError\nimport Foundation\nimport Synchronization\n\n/// An interface that uses NAT to provide an IP address for a given\n/// container/virtual machine.\n@available(macOS 26, *)\npublic final class NATNetworkInterface: Interface, Sendable {\n public var address: String {\n get {\n state.withLock { $0.address }\n }\n set {\n state.withLock { $0.address = newValue }\n }\n\n }\n\n public var gateway: String? {\n get {\n state.withLock { $0.gateway }\n }\n set {\n state.withLock { $0.gateway = newValue }\n }\n }\n\n @available(macOS 26, *)\n public var reference: vmnet_network_ref {\n state.withLock { $0.reference }\n }\n\n public var macAddress: String? {\n get {\n state.withLock { $0.macAddress }\n }\n set {\n state.withLock { $0.macAddress = newValue }\n }\n }\n\n private struct State {\n var address: String\n var gateway: String?\n var reference: vmnet_network_ref!\n var macAddress: String?\n }\n\n private let state: Mutex\n\n @available(macOS 26, *)\n public init(\n address: String,\n gateway: String?,\n reference: sending vmnet_network_ref,\n macAddress: String? = nil\n ) {\n let state = State(\n address: address,\n gateway: gateway,\n reference: reference,\n macAddress: macAddress\n )\n self.state = Mutex(state)\n }\n\n @available(macOS, obsoleted: 26, message: \"Use init(address:gateway:reference:macAddress:) instead\")\n public init(\n address: String,\n gateway: String?,\n macAddress: String? = nil\n ) {\n let state = State(\n address: address,\n gateway: gateway,\n reference: nil,\n macAddress: macAddress\n )\n self.state = Mutex(state)\n }\n}\n\n@available(macOS 26, *)\nextension NATNetworkInterface: VZInterface {\n public func device() throws -> VZVirtioNetworkDeviceConfiguration {\n let config = VZVirtioNetworkDeviceConfiguration()\n if let macAddress = self.macAddress {\n guard let mac = VZMACAddress(string: macAddress) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid mac address \\(macAddress)\")\n }\n config.macAddress = mac\n }\n\n config.attachment = VZVmnetNetworkDeviceAttachment(network: self.reference)\n return config\n }\n}\n\n#endif\n"], ["/containerization/Sources/cctl/KernelCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport Foundation\n\nextension Application {\n struct KernelCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"kernel\",\n abstract: \"Manage kernel images\",\n subcommands: [\n Create.self\n ]\n )\n\n struct Create: AsyncParsableCommand {\n @Option(name: .shortAndLong, help: \"Name for the kernel image\")\n var name: String\n\n @Option(name: .long, help: \"Labels to add to the built image of the form =, [=,...]\")\n var labels: [String] = []\n\n @Argument var kernels: [String]\n\n func run() async throws {\n let imageStore = Application.imageStore\n let contentStore = Application.contentStore\n let labels = Application.parseKeyValuePairs(from: labels)\n let binaries = try parseBinaries()\n _ = try await KernelImage.create(\n reference: name,\n binaries: binaries,\n labels: labels,\n imageStore: imageStore,\n contentStore: contentStore\n )\n }\n\n func parseBinaries() throws -> [Kernel] {\n var binaries = [Kernel]()\n for rawBinary in kernels {\n let parts = rawBinary.split(separator: \":\")\n guard parts.count == 2 else {\n throw \"Invalid binary format: \\(rawBinary)\"\n }\n let platform: SystemPlatform\n switch parts[1] {\n case \"arm64\":\n platform = .linuxArm\n case \"amd64\":\n platform = .linuxAmd\n default:\n fatalError(\"unsupported platform \\(parts[1])\")\n }\n binaries.append(\n .init(\n path: URL(fileURLWithPath: String(parts[0])),\n platform: platform\n )\n )\n }\n return binaries\n }\n }\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/OSFile+Splice.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension OSFile {\n struct SpliceFile: Sendable {\n var file: OSFile\n var offset: Int\n let pipe = Pipe()\n\n var fileDescriptor: Int32 {\n file.fileDescriptor\n }\n\n var reader: Int32 {\n pipe.fileHandleForReading.fileDescriptor\n }\n\n var writer: Int32 {\n pipe.fileHandleForWriting.fileDescriptor\n }\n\n init(fd: Int32) {\n self.file = OSFile(fd: fd)\n self.offset = 0\n }\n\n init(handle: FileHandle) {\n self.file = OSFile(handle: handle)\n self.offset = 0\n }\n\n init(from: OSFile, withOffset: Int = 0) {\n self.file = from\n self.offset = withOffset\n }\n\n func close() throws {\n try self.file.close()\n }\n }\n\n static func splice(from: inout SpliceFile, to: inout SpliceFile, count: Int = 1 << 16) throws -> (read: Int, wrote: Int, action: IOAction) {\n let fromOffset = from.offset\n let toOffset = to.offset\n\n while true {\n while (from.offset - to.offset) < count {\n let toRead = count - (from.offset - to.offset)\n let bytesRead = Foundation.splice(from.fileDescriptor, nil, to.writer, nil, toRead, UInt32(bitPattern: SPLICE_F_MOVE | SPLICE_F_NONBLOCK))\n if bytesRead == -1 {\n if errno != EAGAIN && errno != EIO {\n throw POSIXError(.init(rawValue: errno)!)\n }\n break\n }\n if bytesRead == 0 {\n return (0, 0, .eof)\n }\n from.offset += bytesRead\n if bytesRead < toRead {\n break\n }\n }\n if from.offset == to.offset {\n return (from.offset - fromOffset, to.offset - toOffset, .success)\n }\n while to.offset < from.offset {\n let toWrite = from.offset - to.offset\n let bytesWrote = Foundation.splice(to.reader, nil, to.fileDescriptor, nil, toWrite, UInt32(bitPattern: SPLICE_F_MOVE | SPLICE_F_NONBLOCK))\n if bytesWrote == -1 {\n if errno != EAGAIN && errno != EIO {\n throw POSIXError(.init(rawValue: errno)!)\n }\n break\n }\n to.offset += bytesWrote\n if bytesWrote == 0 {\n return (from.offset - fromOffset, to.offset - toOffset, .brokenPipe)\n }\n if bytesWrote < toWrite {\n break\n }\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/IndexedAddressAllocator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Collections\nimport Synchronization\n\n/// Maps a network address to an array index value, or nil in the case of a domain error.\npackage typealias AddressToIndexTransform = @Sendable (AddressType) -> Int?\n\n/// Maps an array index value to a network address, or nil in the case of a domain error.\npackage typealias IndexToAddressTransform = @Sendable (Int) -> AddressType?\n\npackage final class IndexedAddressAllocator: AddressAllocator {\n private class State {\n var allocations: BitArray\n var enabled: Bool\n var allocationCount: Int\n let addressToIndex: AddressToIndexTransform\n let indexToAddress: IndexToAddressTransform\n\n init(\n size: Int,\n addressToIndex: @escaping AddressToIndexTransform,\n indexToAddress: @escaping IndexToAddressTransform\n ) {\n self.allocations = BitArray.init(repeating: false, count: size)\n self.enabled = true\n self.allocationCount = 0\n self.addressToIndex = addressToIndex\n self.indexToAddress = indexToAddress\n }\n }\n\n private let stateGuard: Mutex\n\n /// Create an allocator with specified size and index mappings.\n package init(\n size: Int,\n addressToIndex: @escaping AddressToIndexTransform,\n indexToAddress: @escaping IndexToAddressTransform\n ) {\n let state = State(\n size: size,\n addressToIndex: addressToIndex,\n indexToAddress: indexToAddress\n )\n self.stateGuard = Mutex(state)\n }\n\n public func allocate() throws -> AddressType {\n try self.stateGuard.withLock { state in\n guard state.enabled else {\n throw AllocatorError.allocatorDisabled\n }\n\n guard let index = state.allocations.firstIndex(of: false) else {\n throw AllocatorError.allocatorFull\n }\n\n guard let address = state.indexToAddress(index) else {\n throw AllocatorError.invalidIndex(index)\n }\n\n state.allocations[index] = true\n state.allocationCount += 1\n return address\n }\n }\n\n package func reserve(_ address: AddressType) throws {\n try self.stateGuard.withLock { state in\n guard state.enabled else {\n throw AllocatorError.allocatorDisabled\n }\n\n guard let index = state.addressToIndex(address) else {\n throw AllocatorError.invalidAddress(address.description)\n }\n\n guard !state.allocations[index] else {\n throw AllocatorError.alreadyAllocated(\"\\(address.description)\")\n }\n\n state.allocations[index] = true\n state.allocationCount += 1\n }\n\n }\n\n package func release(_ address: AddressType) throws {\n try self.stateGuard.withLock { state in\n guard let index = state.addressToIndex(address) else {\n throw AllocatorError.invalidAddress(address.description)\n }\n\n guard state.allocations[index] else {\n throw AllocatorError.notAllocated(\"\\(address.description)\")\n }\n\n state.allocations[index] = false\n state.allocationCount -= 1\n }\n }\n\n package func disableAllocator() -> Bool {\n self.stateGuard.withLock { state in\n guard state.allocationCount == 0 else {\n return false\n }\n state.enabled = false\n return true\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Socket/UnixType.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if canImport(Musl)\nimport Musl\nlet _SOCK_STREAM = SOCK_STREAM\n#elseif canImport(Glibc)\nimport Glibc\nlet _SOCK_STREAM = Int32(SOCK_STREAM.rawValue)\n#elseif canImport(Darwin)\nimport Darwin\nlet _SOCK_STREAM = SOCK_STREAM\n#else\n#error(\"UnixType not supported on this platform.\")\n#endif\n\n/// Unix domain socket variant of `SocketType`.\npublic struct UnixType: SocketType, Sendable, CustomStringConvertible {\n public var domain: Int32 { AF_UNIX }\n public var type: Int32 { _SOCK_STREAM }\n public var description: String {\n path\n }\n\n public let path: String\n public let perms: mode_t?\n private let _addr: sockaddr_un\n private let _unlinkExisting: Bool\n\n private init(sockaddr: sockaddr_un) {\n let pathname: String = withUnsafePointer(to: sockaddr.sun_path) { ptr in\n let charPtr = UnsafeRawPointer(ptr).assumingMemoryBound(to: CChar.self)\n return String(cString: charPtr)\n }\n self._addr = sockaddr\n self.path = pathname\n self._unlinkExisting = false\n self.perms = nil\n }\n\n /// Mode and unlinkExisting only used if the socket is going to be a listening socket.\n public init(\n path: String,\n perms: mode_t? = nil,\n unlinkExisting: Bool = false\n ) throws {\n self.path = path\n self.perms = perms\n self._unlinkExisting = unlinkExisting\n var addr = sockaddr_un()\n addr.sun_family = sa_family_t(AF_UNIX)\n\n let socketName = path\n let nameLength = socketName.utf8.count\n\n #if os(macOS)\n // Funnily enough, this isn't limited by sun path on macOS even though\n // it's stated as so.\n let lengthLimit = 253\n #elseif os(Linux)\n let lengthLimit = MemoryLayout.size(ofValue: addr.sun_path)\n #endif\n\n guard nameLength < lengthLimit else {\n throw Error.nameTooLong(path)\n }\n\n _ = withUnsafeMutablePointer(to: &addr.sun_path.0) { ptr in\n socketName.withCString { strncpy(ptr, $0, nameLength) }\n }\n\n #if os(macOS)\n addr.sun_len = UInt8(MemoryLayout.size + MemoryLayout.size + socketName.utf8.count + 1)\n #endif\n self._addr = addr\n }\n\n public func accept(fd: Int32) throws -> (Int32, SocketType) {\n var clientFD: Int32 = -1\n var addr = sockaddr_un()\n\n clientFD = Syscall.retrying {\n var size = socklen_t(MemoryLayout.stride)\n return withUnsafeMutablePointer(to: &addr) { pointer in\n pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { pointer in\n sysAccept(fd, pointer, &size)\n }\n }\n }\n if clientFD < 0 {\n throw Socket.errnoToError(msg: \"accept failed\")\n }\n\n return (clientFD, UnixType(sockaddr: addr))\n }\n\n public func beforeBind(fd: Int32) throws {\n #if os(Linux)\n // Only Linux supports setting the mode of a socket before binding.\n if let perms = self.perms {\n guard fchmod(fd, perms) == 0 else {\n throw Socket.errnoToError(msg: \"fchmod failed\")\n }\n }\n #endif\n\n var rc: Int32 = 0\n if self._unlinkExisting {\n rc = sysUnlink(self.path)\n if rc != 0 && errno != ENOENT {\n throw Socket.errnoToError(msg: \"failed to remove old socket at \\(self.path)\")\n }\n }\n }\n\n public func beforeListen(fd: Int32) throws {\n #if os(macOS)\n if let perms = self.perms {\n guard chmod(self.path, perms) == 0 else {\n throw Socket.errnoToError(msg: \"chmod failed\")\n }\n }\n #endif\n }\n\n public func withSockAddr(_ closure: (UnsafePointer, UInt32) throws -> Void) throws {\n var addr = self._addr\n try withUnsafePointer(to: &addr) {\n let addrBytes = UnsafeRawPointer($0).assumingMemoryBound(to: sockaddr.self)\n try closure(addrBytes, UInt32(MemoryLayout.stride))\n }\n }\n}\n\nextension UnixType {\n /// `UnixType` errors.\n public enum Error: Swift.Error, CustomStringConvertible {\n case nameTooLong(_: String)\n\n public var description: String {\n switch self {\n case .nameTooLong(let name):\n return \"\\(name) is too long for a Unix Domain Socket path\"\n }\n }\n }\n}\n"], ["/containerization/Sources/Containerization/Image/Image.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\n\n/// Type representing an OCI container image.\npublic struct Image: Sendable {\n private let contentStore: ContentStore\n /// The description for the image that comprises of its name and a reference to its root descriptor.\n public let description: Description\n\n /// A description of the OCI image.\n public struct Description: Sendable {\n /// The string reference of the image.\n public let reference: String\n /// The descriptor identifying the image.\n public let descriptor: Descriptor\n /// The digest for the image.\n public var digest: String { descriptor.digest }\n /// The media type of the image.\n public var mediaType: String { descriptor.mediaType }\n\n public init(reference: String, descriptor: Descriptor) {\n self.reference = reference\n self.descriptor = descriptor\n }\n }\n\n /// The descriptor for the image.\n public var descriptor: Descriptor { description.descriptor }\n /// The digest of the image.\n public var digest: String { description.digest }\n /// The media type of the image.\n public var mediaType: String { description.mediaType }\n /// The string reference for the image.\n public var reference: String { description.reference }\n\n public init(description: Description, contentStore: ContentStore) {\n self.description = description\n self.contentStore = contentStore\n }\n\n /// Returns the underlying OCI index for the image.\n public func index() async throws -> Index {\n guard let content: Content = try await contentStore.get(digest: digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(digest)\")\n }\n return try content.decode()\n }\n\n /// Returns the manifest for the specified platform.\n public func manifest(for platform: Platform) async throws -> Manifest {\n let index = try await self.index()\n let desc = index.manifests.first { desc in\n desc.platform == platform\n }\n guard let desc else {\n throw ContainerizationError(.unsupported, message: \"Platform \\(platform.description)\")\n }\n guard let content: Content = try await contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(digest)\")\n }\n return try content.decode()\n }\n\n /// Returns the descriptor for the given platform. If it does not exist\n /// will throw a ContainerizationError with the code set to .invalidArgument.\n public func descriptor(for platform: Platform) async throws -> Descriptor {\n let index = try await self.index()\n let desc = index.manifests.first { $0.platform == platform }\n guard let desc else {\n throw ContainerizationError(.invalidArgument, message: \"unsupported platform \\(platform)\")\n }\n return desc\n }\n\n /// Returns the OCI config for the specified platform.\n public func config(for platform: Platform) async throws -> ContainerizationOCI.Image {\n let manifest = try await self.manifest(for: platform)\n let desc = manifest.config\n guard let content: Content = try await contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(digest)\")\n }\n return try content.decode()\n }\n\n /// Returns a list of digests to all the referenced OCI objects.\n public func referencedDigests() async throws -> [String] {\n var referenced: [String] = [self.digest.trimmingDigestPrefix]\n let index = try await self.index()\n for manifest in index.manifests {\n referenced.append(manifest.digest.trimmingDigestPrefix)\n guard let m: Manifest = try? await contentStore.get(digest: manifest.digest) else {\n // If the requested digest does not exist or is not a manifest. Skip.\n // Its safe to skip processing this digest as it wont have any child layers.\n continue\n }\n let descs = m.layers + [m.config]\n referenced.append(contentsOf: descs.map { $0.digest.trimmingDigestPrefix })\n }\n return referenced\n }\n\n /// Returns a reference to the content blob for the image. The specified digest must be referenced by the image in one of its layers.\n public func getContent(digest: String) async throws -> Content {\n guard try await self.referencedDigests().contains(digest.trimmingDigestPrefix) else {\n throw ContainerizationError(.internalError, message: \"Image \\(self.reference) does not reference digest \\(digest)\")\n }\n guard let content: Content = try await contentStore.get(digest: digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(digest)\")\n }\n return content\n }\n}\n"], ["/containerization/Sources/cctl/RootfsCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationEXT4\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\n\nextension Application {\n struct Rootfs: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"rootfs\",\n abstract: \"Manage the root filesystem for a container\",\n subcommands: [\n Create.self\n ]\n )\n\n struct Create: AsyncParsableCommand {\n @Option(name: .long, help: \"Path to vminitd\")\n var vminitd: String\n\n @Option(name: .long, help: \"Path to vmexec\")\n var vmexec: String\n\n @Option(name: .long, help: \"Platform of the built binaries being packaged into the block\")\n var platformString: String = Platform.current.description\n\n @Option(name: .long, help: \"Labels to add to the built image of the form =, [=,...]\")\n var labels: [String] = []\n\n @Argument var rootfsPath: String\n\n @Argument var tag: String\n\n private static let directories = [\n \"bin\",\n \"sbin\",\n \"dev\",\n \"sys\",\n \"proc/self\", // hack for swift init's booting\n \"run\",\n \"tmp\",\n \"mnt\",\n \"var\",\n ]\n\n func run() async throws {\n try await writeArchive()\n let p = try Platform(from: platformString)\n let rootfs = URL(filePath: rootfsPath)\n let labels = Application.parseKeyValuePairs(from: labels)\n _ = try await InitImage.create(\n reference: tag, rootfs: rootfs,\n platform: p, labels: labels,\n imageStore: Application.imageStore,\n contentStore: Application.contentStore)\n }\n\n private func writeArchive() async throws {\n let writer = try ArchiveWriter(format: .pax, filter: .gzip, file: URL(filePath: rootfsPath))\n let ts = Date()\n let entry = WriteEntry()\n entry.permissions = 0o755\n entry.modificationDate = ts\n entry.creationDate = ts\n entry.group = 0\n entry.owner = 0\n entry.fileType = .directory\n // create the initial directory structure.\n for dir in Self.directories {\n entry.path = dir\n try writer.writeEntry(entry: entry, data: nil)\n }\n\n entry.fileType = .regular\n entry.path = \"sbin/vminitd\"\n\n var src = URL(fileURLWithPath: vminitd)\n var data = try Data(contentsOf: src)\n entry.size = Int64(data.count)\n try writer.writeEntry(entry: entry, data: data)\n\n src = URL(fileURLWithPath: vmexec)\n data = try Data(contentsOf: src)\n entry.path = \"sbin/vmexec\"\n entry.size = Int64(data.count)\n try writer.writeEntry(entry: entry, data: data)\n\n entry.fileType = .symbolicLink\n entry.path = \"proc/self/exe\"\n entry.symlinkTarget = \"sbin/vminitd\"\n entry.size = nil\n try writer.writeEntry(entry: entry, data: data)\n try writer.finishEncoding()\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Socket/VsockType.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CShim\n\n#if canImport(Musl)\nimport Musl\n#elseif canImport(Glibc)\nimport Glibc\n#elseif canImport(Darwin)\nimport Darwin\n#else\n#error(\"VsockType not supported on this platform.\")\n#endif\n\n/// Vsock variant of `SocketType`.\npublic struct VsockType: SocketType, Sendable {\n public var domain: Int32 { AF_VSOCK }\n public var type: Int32 { _SOCK_STREAM }\n public var description: String {\n \"\\(cid):\\(port)\"\n }\n\n public static let anyCID: UInt32 = UInt32(bitPattern: -1)\n public static let hypervisorCID: UInt32 = 0x0\n // Supported on Linux 5.6+; otherwise, will need to use getLocalCID().\n public static let localCID: UInt32 = 0x1\n public static let hostCID: UInt32 = 0x2\n\n // socketFD is unused on Linux.\n public static func getLocalCID(socketFD: Int32) throws -> UInt32 {\n let request = VsockLocalCIDIoctl\n #if os(Linux)\n let fd = open(\"/dev/vsock\", O_RDONLY | O_CLOEXEC)\n if fd == -1 {\n throw Socket.errnoToError(msg: \"failed to open /dev/vsock\")\n }\n defer { close(fd) }\n #else\n let fd = socketFD\n #endif\n var cid: UInt32 = 0\n guard sysIoctl(fd, numericCast(request), &cid) != -1 else {\n throw Socket.errnoToError(msg: \"failed to get local cid\")\n }\n return cid\n }\n\n public let port: UInt32\n public let cid: UInt32\n\n private let _addr: sockaddr_vm\n\n public init(port: UInt32, cid: UInt32) {\n self.cid = cid\n self.port = port\n var sockaddr = sockaddr_vm()\n sockaddr.svm_family = sa_family_t(AF_VSOCK)\n sockaddr.svm_cid = cid\n sockaddr.svm_port = port\n self._addr = sockaddr\n }\n\n private init(sockaddr: sockaddr_vm) {\n self._addr = sockaddr\n self.cid = sockaddr.svm_cid\n self.port = sockaddr.svm_port\n }\n\n public func accept(fd: Int32) throws -> (Int32, SocketType) {\n var clientFD: Int32 = -1\n var addr = sockaddr_vm()\n\n while clientFD < 0 {\n var size = socklen_t(MemoryLayout.stride)\n clientFD = withUnsafeMutablePointer(to: &addr) { pointer in\n pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { pointer in\n sysAccept(fd, pointer, &size)\n }\n }\n if clientFD < 0 && errno != EINTR {\n throw Socket.errnoToError(msg: \"accept failed\")\n }\n }\n return (clientFD, VsockType(sockaddr: addr))\n }\n\n public func withSockAddr(_ closure: (UnsafePointer, UInt32) throws -> Void) throws {\n var addr = self._addr\n try withUnsafePointer(to: &addr) {\n let addrBytes = UnsafeRawPointer($0).assumingMemoryBound(to: sockaddr.self)\n try closure(addrBytes, UInt32(MemoryLayout.stride))\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/RotatingAddressAllocator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Synchronization\n\npackage final class RotatingAddressAllocator: AddressAllocator {\n package typealias AddressType = UInt32\n\n private struct State {\n var allocations: [AddressType]\n var enabled: Bool\n var allocationCount: Int\n let addressToIndex: AddressToIndexTransform\n let indexToAddress: IndexToAddressTransform\n\n init(\n size: UInt32,\n addressToIndex: @escaping AddressToIndexTransform,\n indexToAddress: @escaping IndexToAddressTransform\n ) {\n self.allocations = [UInt32](0..\n\n /// Create an allocator with specified size and index mappings.\n package init(\n size: UInt32,\n addressToIndex: @escaping AddressToIndexTransform,\n indexToAddress: @escaping IndexToAddressTransform\n ) {\n let state = State(\n size: size,\n addressToIndex: addressToIndex,\n indexToAddress: indexToAddress\n )\n self.stateGuard = Mutex(state)\n }\n\n public func allocate() throws -> AddressType {\n try self.stateGuard.withLock { state in\n guard state.enabled else {\n throw AllocatorError.allocatorDisabled\n }\n\n guard state.allocations.count > 0 else {\n throw AllocatorError.allocatorFull\n }\n\n let value = state.allocations.removeFirst()\n\n guard let address = state.indexToAddress(Int(value)) else {\n throw AllocatorError.invalidIndex(Int(value))\n }\n\n state.allocationCount += 1\n return address\n }\n }\n\n package func reserve(_ address: AddressType) throws {\n try self.stateGuard.withLock { state in\n guard state.enabled else {\n throw AllocatorError.allocatorDisabled\n }\n\n guard let index = state.addressToIndex(address) else {\n throw AllocatorError.invalidAddress(address.description)\n }\n\n let i = state.allocations.firstIndex(of: UInt32(index))\n guard let i else {\n throw AllocatorError.alreadyAllocated(\"\\(address.description)\")\n }\n\n _ = state.allocations.remove(at: i)\n state.allocationCount += 1\n }\n }\n\n package func release(_ address: AddressType) throws {\n try self.stateGuard.withLock { state in\n guard let index = (state.addressToIndex(address)) else {\n throw AllocatorError.invalidAddress(address.description)\n }\n let value = UInt32(index)\n\n guard !state.allocations.contains(value) else {\n throw AllocatorError.notAllocated(\"\\(address.description)\")\n }\n\n state.allocations.append(value)\n state.allocationCount -= 1\n }\n }\n\n package func disableAllocator() -> Bool {\n self.stateGuard.withLock { state in\n guard state.allocationCount == 0 else {\n return false\n }\n state.enabled = false\n return true\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationError/ContainerizationError.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// The core error type for Containerization.\n///\n/// Most API surfaces for the core container/process/agent types will\n/// return a ContainerizationError.\npublic struct ContainerizationError: Swift.Error, Sendable {\n /// A code describing the error encountered.\n public var code: Code\n /// A description of the error.\n public var message: String\n /// The original error which led to this error being thrown.\n public var cause: (any Error)?\n\n /// Creates a new error.\n ///\n /// - Parameters:\n /// - code: The error code.\n /// - message: A description of the error.\n /// - cause: The original error which led to this error being thrown.\n public init(_ code: Code, message: String, cause: (any Error)? = nil) {\n self.code = code\n self.message = message\n self.cause = cause\n }\n\n /// Creates a new error.\n ///\n /// - Parameters:\n /// - rawCode: The error code value as a String.\n /// - message: A description of the error.\n /// - cause: The original error which led to this error being thrown.\n public init(_ rawCode: String, message: String, cause: (any Error)? = nil) {\n self.code = Code(rawValue: rawCode)\n self.message = message\n self.cause = cause\n }\n\n /// Provides a unique hash of the error.\n public func hash(into hasher: inout Hasher) {\n hasher.combine(self.code)\n hasher.combine(self.message)\n }\n\n /// Equality operator for the error. Uses the code and message.\n public static func == (lhs: Self, rhs: Self) -> Bool {\n lhs.code == rhs.code && lhs.message == rhs.message\n }\n\n /// Checks if the given error has the provided code.\n public func isCode(_ code: Code) -> Bool {\n self.code == code\n }\n}\n\nextension ContainerizationError: CustomStringConvertible {\n /// Description of the error.\n public var description: String {\n guard let cause = self.cause else {\n return \"\\(self.code): \\\"\\(self.message)\\\"\"\n }\n return \"\\(self.code): \\\"\\(self.message)\\\" (cause: \\\"\\(cause)\\\")\"\n }\n}\n\nextension ContainerizationError {\n /// Codes for a `ContainerizationError`.\n public struct Code: Sendable, Hashable {\n private enum Value: Hashable, Sendable, CaseIterable {\n case unknown\n case invalidArgument\n case internalError\n case exists\n case notFound\n case cancelled\n case invalidState\n case empty\n case timeout\n case unsupported\n case interrupted\n }\n\n private var value: Value\n private init(_ value: Value) {\n self.value = value\n }\n\n init(rawValue: String) {\n let values = Value.allCases.reduce(into: [String: Value]()) {\n $0[String(describing: $1)] = $1\n }\n\n let match = values[rawValue]\n guard let match else {\n fatalError(\"invalid Code Value \\(rawValue)\")\n }\n self.value = match\n }\n\n public static var unknown: Self {\n Self(.unknown)\n }\n\n public static var invalidArgument: Self {\n Self(.invalidArgument)\n }\n\n public static var internalError: Self {\n Self(.internalError)\n }\n\n public static var exists: Self {\n Self(.exists)\n }\n\n public static var notFound: Self {\n Self(.notFound)\n }\n\n public static var cancelled: Self {\n Self(.cancelled)\n }\n\n public static var invalidState: Self {\n Self(.invalidState)\n }\n\n public static var empty: Self {\n Self(.empty)\n }\n\n public static var timeout: Self {\n Self(.timeout)\n }\n\n public static var unsupported: Self {\n Self(.unsupported)\n }\n\n public static var interrupted: Self {\n Self(.interrupted)\n }\n }\n}\n\nextension ContainerizationError.Code: CustomStringConvertible {\n public var description: String {\n String(describing: self.value)\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+FileTree.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\nextension EXT4 {\n class FileTree {\n class FileTreeNode {\n let inode: InodeNumber\n let name: String\n var children: [Ptr] = []\n var blocks: (start: UInt32, end: UInt32)?\n var additionalBlocks: [(start: UInt32, end: UInt32)]?\n var link: InodeNumber?\n private var parent: Ptr?\n\n init(\n inode: InodeNumber,\n name: String,\n parent: Ptr?,\n children: [Ptr] = [],\n blocks: (start: UInt32, end: UInt32)? = nil,\n additionalBlocks: [(start: UInt32, end: UInt32)]? = nil,\n link: InodeNumber? = nil\n ) {\n self.inode = inode\n self.name = name\n self.children = children\n self.blocks = blocks\n self.additionalBlocks = additionalBlocks\n self.link = link\n self.parent = parent\n }\n\n deinit {\n self.children.removeAll()\n self.children = []\n self.blocks = nil\n self.additionalBlocks = nil\n self.link = nil\n }\n\n var path: FilePath? {\n var components: [String] = [self.name]\n var _ptr = self.parent\n while let ptr = _ptr {\n components.append(ptr.pointee.name)\n _ptr = ptr.pointee.parent\n }\n guard let last = components.last else {\n return nil\n }\n guard components.count > 1 else {\n return FilePath(last)\n }\n components = components.dropLast()\n let path = components.reversed().joined(separator: \"/\")\n guard let data = path.data(using: .utf8) else {\n return nil\n }\n guard let dataPath = String(data: data, encoding: .utf8) else {\n return nil\n }\n return FilePath(dataPath).pushing(FilePath(last)).lexicallyNormalized()\n }\n }\n\n var root: Ptr\n\n init(_ root: InodeNumber, _ name: String) {\n self.root = Ptr.allocate(capacity: 1)\n self.root.initialize(to: FileTreeNode(inode: root, name: name, parent: nil))\n }\n\n func lookup(path: FilePath) -> Ptr? {\n var components: [String] = path.items\n var node = self.root\n if components.first == \"/\" {\n components = Array(components.dropFirst())\n }\n if components.count == 0 {\n return node\n }\n for component in components {\n var found = false\n for childPtr in node.pointee.children {\n let child = childPtr.pointee\n if child.name == component {\n node = childPtr\n found = true\n break\n }\n }\n guard found else {\n return nil\n }\n }\n return node\n }\n }\n}\n"], ["/containerization/Sources/Containerization/Agent/Vminitd+SocketRelay.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension Vminitd: SocketRelayAgent {\n /// Sets up a relay between a host socket to a newly created guest socket, or vice versa.\n public func relaySocket(port: UInt32, configuration: UnixSocketConfiguration) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest.with {\n $0.id = configuration.id\n $0.vsockPort = port\n\n if let perms = configuration.permissions {\n $0.guestSocketPermissions = UInt32(perms.rawValue)\n }\n\n switch configuration.direction {\n case .into:\n $0.guestPath = configuration.destination.path\n $0.action = .into\n case .outOf:\n $0.guestPath = configuration.source.path\n $0.action = .outOf\n }\n }\n _ = try await client.proxyVsock(request)\n }\n\n /// Stops the specified socket relay.\n public func stopSocketRelay(configuration: UnixSocketConfiguration) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest.with {\n $0.id = configuration.id\n }\n _ = try await client.stopVsockProxy(request)\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/WriteEntry.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CArchive\nimport Foundation\n\n/// Represents a single entry (e.g., a file, directory, symbolic link)\n/// that is to be read/written into an archive.\npublic final class WriteEntry {\n let underlying: OpaquePointer\n\n public init(_ archive: ArchiveWriter) {\n underlying = archive_entry_new2(archive.underlying)\n }\n\n public init() {\n underlying = archive_entry_new()\n }\n\n deinit {\n archive_entry_free(underlying)\n }\n}\n\nextension WriteEntry {\n /// The size of the entry in bytes.\n public var size: Int64? {\n get {\n guard archive_entry_size_is_set(underlying) != 0 else { return nil }\n return archive_entry_size(underlying)\n }\n set {\n if let s = newValue {\n archive_entry_set_size(underlying, s)\n } else {\n archive_entry_unset_size(underlying)\n }\n }\n }\n\n /// The mode of the entry.\n public var permissions: mode_t {\n get {\n archive_entry_perm(underlying)\n }\n set {\n archive_entry_set_perm(underlying, newValue)\n }\n }\n\n /// The owner id of the entry.\n public var owner: uid_t? {\n get {\n uid_t(exactly: archive_entry_uid(underlying))\n }\n set {\n archive_entry_set_uid(underlying, Int64(newValue ?? 0))\n }\n }\n\n /// The group id of the entry\n public var group: gid_t? {\n get {\n gid_t(exactly: archive_entry_gid(underlying))\n }\n set {\n archive_entry_set_gid(underlying, Int64(newValue ?? 0))\n }\n }\n\n /// The path of file this entry hardlinks to\n public var hardlink: String? {\n get {\n guard let cstr = archive_entry_hardlink(underlying) else {\n return nil\n }\n return String(cString: cstr)\n }\n set {\n guard let newValue else {\n archive_entry_set_hardlink(underlying, nil)\n return\n }\n newValue.withCString {\n archive_entry_set_hardlink(underlying, $0)\n }\n }\n }\n\n /// The UTF-8 encoded path of file this entry hardlinks to\n public var hardlinkUtf8: String? {\n get {\n guard let cstr = archive_entry_hardlink_utf8(underlying) else {\n return nil\n }\n return String(cString: cstr, encoding: .utf8)\n }\n set {\n guard let newValue else {\n archive_entry_set_hardlink_utf8(underlying, nil)\n return\n }\n newValue.withCString {\n archive_entry_set_hardlink_utf8(underlying, $0)\n }\n }\n }\n\n /// The string representation of the permissions of the entry\n public var strmode: String? {\n if let cstr = archive_entry_strmode(underlying) {\n return String(cString: cstr)\n }\n return nil\n }\n\n /// The type of file this entry represents.\n public var fileType: URLFileResourceType {\n get {\n switch archive_entry_filetype(underlying) {\n case S_IFIFO: return .namedPipe\n case S_IFCHR: return .characterSpecial\n case S_IFDIR: return .directory\n case S_IFBLK: return .blockSpecial\n case S_IFREG: return .regular\n case S_IFLNK: return .symbolicLink\n case S_IFSOCK: return .socket\n default: return .unknown\n }\n }\n set {\n switch newValue {\n case .namedPipe: archive_entry_set_filetype(underlying, UInt32(S_IFIFO as mode_t))\n case .characterSpecial: archive_entry_set_filetype(underlying, UInt32(S_IFCHR as mode_t))\n case .directory: archive_entry_set_filetype(underlying, UInt32(S_IFDIR as mode_t))\n case .blockSpecial: archive_entry_set_filetype(underlying, UInt32(S_IFBLK as mode_t))\n case .regular: archive_entry_set_filetype(underlying, UInt32(S_IFREG as mode_t))\n case .symbolicLink: archive_entry_set_filetype(underlying, UInt32(S_IFLNK as mode_t))\n case .socket: archive_entry_set_filetype(underlying, UInt32(S_IFSOCK as mode_t))\n default: archive_entry_set_filetype(underlying, 0)\n }\n }\n }\n\n /// The date that the entry was last accessed\n public var contentAccessDate: Date? {\n get {\n Date(\n underlying,\n archive_entry_atime_is_set,\n archive_entry_atime,\n archive_entry_atime_nsec)\n }\n set {\n setDate(\n newValue,\n underlying, archive_entry_set_atime,\n archive_entry_unset_atime)\n }\n }\n\n /// The date that the entry was created\n public var creationDate: Date? {\n get {\n Date(\n underlying,\n archive_entry_ctime_is_set,\n archive_entry_ctime,\n archive_entry_ctime_nsec)\n }\n set {\n setDate(\n newValue,\n underlying, archive_entry_set_ctime,\n archive_entry_unset_ctime)\n }\n }\n\n /// The date that the entry was modified\n public var modificationDate: Date? {\n get {\n Date(\n underlying,\n archive_entry_mtime_is_set,\n archive_entry_mtime,\n archive_entry_mtime_nsec)\n }\n set {\n setDate(\n newValue,\n underlying, archive_entry_set_mtime,\n archive_entry_unset_mtime)\n }\n }\n\n /// The file path of the entry\n public var path: String? {\n get {\n guard let pathname = archive_entry_pathname(underlying) else {\n return nil\n }\n return String(cString: pathname)\n }\n set {\n guard let newValue else {\n archive_entry_set_pathname(underlying, nil)\n return\n }\n newValue.withCString {\n archive_entry_set_pathname(underlying, $0)\n }\n }\n }\n\n /// The UTF-8 encoded file path of the entry\n public var pathUtf8: String? {\n get {\n guard let pathname = archive_entry_pathname_utf8(underlying) else {\n return nil\n }\n return String(cString: pathname)\n }\n set {\n guard let newValue else {\n archive_entry_set_pathname_utf8(underlying, nil)\n return\n }\n newValue.withCString {\n archive_entry_set_pathname_utf8(underlying, $0)\n }\n }\n }\n\n /// The symlink target that the entry points to\n public var symlinkTarget: String? {\n get {\n guard let target = archive_entry_symlink(underlying) else {\n return nil\n }\n return String(cString: target)\n }\n set {\n guard let newValue else {\n archive_entry_set_symlink(underlying, nil)\n return\n }\n newValue.withCString {\n archive_entry_set_symlink(underlying, $0)\n }\n }\n }\n\n /// The extended attributes of the entry\n public var xattrs: [String: Data] {\n get {\n archive_entry_xattr_reset(self.underlying)\n var attrs: [String: Data] = [:]\n var namePtr: UnsafePointer?\n var valuePtr: UnsafeRawPointer?\n var size: Int = 0\n while archive_entry_xattr_next(self.underlying, &namePtr, &valuePtr, &size) == 0 {\n let _name = namePtr.map { String(cString: $0) }\n let _value = valuePtr.map { Data(bytes: $0, count: size) }\n guard let name = _name, let value = _value else {\n continue\n }\n attrs[name] = value\n }\n return attrs\n }\n set {\n archive_entry_xattr_clear(self.underlying)\n for (key, value) in newValue {\n value.withUnsafeBytes { ptr in\n archive_entry_xattr_add_entry(self.underlying, key, ptr.baseAddress, [UInt8](value).count)\n }\n }\n }\n }\n\n fileprivate func setDate(\n _ date: Date?, _ underlying: OpaquePointer, _ setter: (OpaquePointer, time_t, CLong) -> Void,\n _ unset: (OpaquePointer) -> Void\n ) {\n if let d = date {\n let ti = d.timeIntervalSince1970\n let seconds = floor(ti)\n let nsec = max(0, min(1_000_000_000, ti - seconds * 1_000_000_000))\n setter(underlying, time_t(seconds), CLong(nsec))\n } else {\n unset(underlying)\n }\n }\n}\n\nextension Date {\n init?(\n _ underlying: OpaquePointer, _ isSet: (OpaquePointer) -> CInt, _ seconds: (OpaquePointer) -> time_t,\n _ nsec: (OpaquePointer) -> CLong\n ) {\n guard isSet(underlying) != 0 else { return nil }\n let ti = TimeInterval(seconds(underlying)) + TimeInterval(nsec(underlying)) * 0.000_000_001\n self.init(timeIntervalSince1970: ti)\n }\n}\n"], ["/containerization/Sources/Containerization/Image/KernelImage.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\n/// A multi-arch kernel image represented by an OCI image.\npublic struct KernelImage: Sendable {\n /// The media type for a kernel image.\n public static let mediaType = \"application/vnd.apple.containerization.kernel\"\n\n /// The name or reference of the image.\n public var name: String { image.reference }\n\n let image: Image\n\n public init(image: Image) {\n self.image = image\n }\n}\n\nextension KernelImage {\n /// Return the kernel from a multi arch image for a specific system platform.\n public func kernel(for platform: SystemPlatform) async throws -> Kernel {\n let manifest = try await image.manifest(for: platform.ociPlatform())\n guard let descriptor = manifest.layers.first, descriptor.mediaType == Self.mediaType else {\n throw ContainerizationError(.notFound, message: \"kernel descriptor for \\(platform) not found\")\n }\n let content = try await image.getContent(digest: descriptor.digest)\n return Kernel(\n path: content.path,\n platform: platform\n )\n }\n\n /// Create a new kernel image with the reference as the name.\n /// This will create a multi arch image containing kernel's for each provided architecture.\n public static func create(reference: String, binaries: [Kernel], labels: [String: String] = [:], imageStore: ImageStore, contentStore: ContentStore) async throws -> KernelImage\n {\n let indexDescriptorStore = AsyncStore()\n try await contentStore.ingest { ingestPath in\n var descriptors = [Descriptor]()\n let writer = try ContentWriter(for: ingestPath)\n\n for kernel in binaries {\n var result = try writer.create(from: kernel.path)\n let platform = kernel.platform.ociPlatform()\n let layerDescriptor = Descriptor(\n mediaType: mediaType,\n digest: result.digest.digestString,\n size: result.size,\n platform: platform)\n let rootfsConfig = ContainerizationOCI.Rootfs(type: \"layers\", diffIDs: [result.digest.digestString])\n let runtimeConfig = ContainerizationOCI.ImageConfig(labels: labels)\n let imageConfig = ContainerizationOCI.Image(architecture: platform.architecture, os: platform.os, config: runtimeConfig, rootfs: rootfsConfig)\n\n result = try writer.create(from: imageConfig)\n let configDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.imageConfig, digest: result.digest.digestString, size: result.size)\n\n let manifest = Manifest(config: configDescriptor, layers: [layerDescriptor])\n result = try writer.create(from: manifest)\n let manifestDescriptor = Descriptor(\n mediaType: ContainerizationOCI.MediaTypes.imageManifest, digest: result.digest.digestString, size: result.size, platform: platform)\n descriptors.append(manifestDescriptor)\n }\n let index = ContainerizationOCI.Index(manifests: descriptors)\n let result = try writer.create(from: index)\n let indexDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.index, digest: result.digest.digestString, size: result.size)\n await indexDescriptorStore.set(indexDescriptor)\n }\n\n guard let indexDescriptor = await indexDescriptorStore.get() else {\n throw ContainerizationError(.notFound, message: \"image for \\(reference) not found\")\n }\n\n let description = Image.Description(reference: reference, descriptor: indexDescriptor)\n let image = try await imageStore.create(description: description)\n return KernelImage(image: image)\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/RegistryClient+Error.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport Foundation\nimport NIOHTTP1\n\nextension RegistryClient {\n /// `RegistryClient` errors.\n public enum Error: Swift.Error, CustomStringConvertible {\n case invalidStatus(url: String, HTTPResponseStatus, reason: String? = nil)\n\n /// Description of the errors.\n public var description: String {\n switch self {\n case .invalidStatus(let u, let response, let reason):\n return \"HTTP request to \\(u) failed with response: \\(response.description). Reason: \\(reason ?? \"Unknown\")\"\n }\n }\n }\n\n /// The container registry typically returns actionable failure reasons in the response body\n /// of the failing HTTP Request. This type models the structure of the error message.\n /// Reference: https://distribution.github.io/distribution/spec/api/#errors\n internal struct ErrorResponse: Codable {\n let errors: [RemoteError]\n\n internal struct RemoteError: Codable {\n let code: String\n let message: String\n let detail: String?\n }\n\n internal static func fromResponseBody(_ body: HTTPClientResponse.Body) async -> ErrorResponse? {\n guard var buffer = try? await body.collect(upTo: Int(1.mib())) else {\n return nil\n }\n guard let bytes = buffer.readBytes(length: buffer.readableBytes) else {\n return nil\n }\n let data = Data(bytes)\n guard let jsonError = try? JSONDecoder().decode(ErrorResponse.self, from: data) else {\n return nil\n }\n return jsonError\n }\n\n public var jsonString: String {\n let data = try? JSONEncoder().encode(self)\n guard let data else {\n return \"{}\"\n }\n return String(data: data, encoding: .utf8) ?? \"{}\"\n }\n }\n}\n"], ["/containerization/Sources/Containerization/Image/Unpacker/EXT4Unpacker.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\n#if os(macOS)\nimport ContainerizationArchive\nimport ContainerizationEXT4\nimport SystemPackage\n#endif\n\npublic struct EXT4Unpacker: Unpacker {\n let blockSizeInBytes: UInt64\n\n public init(blockSizeInBytes: UInt64) {\n self.blockSizeInBytes = blockSizeInBytes\n }\n\n public func unpack(_ image: Image, for platform: Platform, at path: URL, progress: ProgressHandler? = nil) async throws -> Mount {\n #if !os(macOS)\n throw ContainerizationError(.unsupported, message: \"Cannot unpack an image on current platform\")\n #else\n let blockPath = try prepareUnpackPath(path: path)\n let manifest = try await image.manifest(for: platform)\n let filesystem = try EXT4.Formatter(FilePath(path), minDiskSize: blockSizeInBytes)\n defer { try? filesystem.close() }\n\n for layer in manifest.layers {\n try Task.checkCancellation()\n let content = try await image.getContent(digest: layer.digest)\n\n let compression: ContainerizationArchive.Filter\n switch layer.mediaType {\n case MediaTypes.imageLayer, MediaTypes.dockerImageLayer:\n compression = .none\n case MediaTypes.imageLayerGzip, MediaTypes.dockerImageLayerGzip:\n compression = .gzip\n default:\n throw ContainerizationError(.unsupported, message: \"Media type \\(layer.mediaType) not supported.\")\n }\n try filesystem.unpack(\n source: content.path,\n format: .paxRestricted,\n compression: compression,\n progress: progress\n )\n }\n\n return .block(\n format: \"ext4\",\n source: blockPath,\n destination: \"/\",\n options: []\n )\n #endif\n }\n\n private func prepareUnpackPath(path: URL) throws -> String {\n let blockPath = path.absolutePath()\n guard !FileManager.default.fileExists(atPath: blockPath) else {\n throw ContainerizationError(.exists, message: \"block device already exists at \\(blockPath)\")\n }\n return blockPath\n }\n}\n"], ["/containerization/Sources/Containerization/IO/Terminal+ReaderStream.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\n\nextension Terminal: ReaderStream {\n public func stream() -> AsyncStream {\n .init { cont in\n self.handle.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n self.handle.readabilityHandler = nil\n cont.finish()\n return\n }\n cont.yield(data)\n }\n }\n }\n}\n\nextension Terminal: Writer {}\n"], ["/containerization/Sources/ContainerizationOCI/Spec.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// NOTE: This is not a complete recreation of the runtime spec. Other platforms outside of Linux\n/// have been left off, and some APIs for Linux aren't present. This was manually ported starting\n/// at the v1.2.0 release.\n\npublic struct Spec: Codable, Sendable {\n public var version: String\n public var hooks: Hook?\n public var process: Process?\n public var hostname, domainname: String\n public var mounts: [Mount]\n public var annotations: [String: String]?\n public var root: Root?\n public var linux: Linux?\n\n public init(\n version: String = \"\",\n hooks: Hook? = nil,\n process: Process? = nil,\n hostname: String = \"\",\n domainname: String = \"\",\n mounts: [Mount] = [],\n annotations: [String: String]? = nil,\n root: Root? = nil,\n linux: Linux? = nil\n ) {\n self.version = version\n self.hooks = hooks\n self.process = process\n self.hostname = hostname\n self.domainname = domainname\n self.mounts = mounts\n self.annotations = annotations\n self.root = root\n self.linux = linux\n }\n\n public enum CodingKeys: String, CodingKey {\n case version = \"ociVersion\"\n case hooks\n case process\n case hostname\n case domainname\n case mounts\n case annotations\n case root\n case linux\n }\n}\n\npublic struct Process: Codable, Sendable {\n public var cwd: String\n public var env: [String]\n public var consoleSize: Box?\n public var selinuxLabel: String\n public var noNewPrivileges: Bool\n public var commandLine: String\n public var oomScoreAdj: Int?\n public var capabilities: LinuxCapabilities?\n public var apparmorProfile: String\n public var user: User\n public var rlimits: [POSIXRlimit]\n public var args: [String]\n public var terminal: Bool\n\n public init(\n args: [String] = [],\n cwd: String = \"/\",\n env: [String] = [],\n consoleSize: Box? = nil,\n selinuxLabel: String = \"\",\n noNewPrivileges: Bool = false,\n commandLine: String = \"\",\n oomScoreAdj: Int? = nil,\n capabilities: LinuxCapabilities? = nil,\n apparmorProfile: String = \"\",\n user: User = .init(),\n rlimits: [POSIXRlimit] = [],\n terminal: Bool = false\n ) {\n self.cwd = cwd\n self.env = env\n self.consoleSize = consoleSize\n self.selinuxLabel = selinuxLabel\n self.noNewPrivileges = noNewPrivileges\n self.commandLine = commandLine\n self.oomScoreAdj = oomScoreAdj\n self.capabilities = capabilities\n self.apparmorProfile = apparmorProfile\n self.user = user\n self.rlimits = rlimits\n self.args = args\n self.terminal = terminal\n }\n\n public init(from config: ImageConfig) {\n let cwd = config.workingDir ?? \"/\"\n let env = config.env ?? []\n let args = (config.entrypoint ?? []) + (config.cmd ?? [])\n let user: User = {\n if let rawString = config.user {\n return User(username: rawString)\n }\n return User()\n }()\n self.init(args: args, cwd: cwd, env: env, user: user)\n }\n}\n\npublic struct LinuxCapabilities: Codable, Sendable {\n public var bounding: [String]\n public var effective: [String]\n public var inheritable: [String]\n public var permitted: [String]\n public var ambient: [String]\n\n public init(\n bounding: [String],\n effective: [String],\n inheritable: [String],\n permitted: [String],\n ambient: [String]\n ) {\n self.bounding = bounding\n self.effective = effective\n self.inheritable = inheritable\n self.permitted = permitted\n self.ambient = ambient\n }\n}\n\npublic struct Box: Codable, Sendable {\n var height, width: UInt\n\n public init(height: UInt, width: UInt) {\n self.height = height\n self.width = width\n }\n}\n\npublic struct User: Codable, Sendable {\n public var uid: UInt32\n public var gid: UInt32\n public var umask: UInt32?\n public var additionalGids: [UInt32]\n public var username: String\n\n public init(\n uid: UInt32 = 0,\n gid: UInt32 = 0,\n umask: UInt32? = nil,\n additionalGids: [UInt32] = [],\n username: String = \"\"\n ) {\n self.uid = uid\n self.gid = gid\n self.umask = umask\n self.additionalGids = additionalGids\n self.username = username\n }\n}\n\npublic struct Root: Codable, Sendable {\n public var path: String\n public var readonly: Bool\n\n public init(path: String, readonly: Bool) {\n self.path = path\n self.readonly = readonly\n }\n}\n\npublic struct Mount: Codable, Sendable {\n public var type: String\n public var source: String\n public var destination: String\n public var options: [String]\n\n public var uidMappings: [LinuxIDMapping]\n public var gidMappings: [LinuxIDMapping]\n\n public init(\n type: String,\n source: String,\n destination: String,\n options: [String] = [],\n uidMappings: [LinuxIDMapping] = [],\n gidMappings: [LinuxIDMapping] = []\n ) {\n self.destination = destination\n self.type = type\n self.source = source\n self.options = options\n self.uidMappings = uidMappings\n self.gidMappings = gidMappings\n }\n}\n\npublic struct Hook: Codable, Sendable {\n public var path: String\n public var args: [String]\n public var env: [String]\n public var timeout: Int?\n\n public init(path: String, args: [String], env: [String], timeout: Int?) {\n self.path = path\n self.args = args\n self.env = env\n self.timeout = timeout\n }\n}\n\npublic struct Hooks: Codable, Sendable {\n public var prestart: [Hook]\n public var createRuntime: [Hook]\n public var createContainer: [Hook]\n public var startContainer: [Hook]\n public var poststart: [Hook]\n public var poststop: [Hook]\n\n public init(\n prestart: [Hook],\n createRuntime: [Hook],\n createContainer: [Hook],\n startContainer: [Hook],\n poststart: [Hook],\n poststop: [Hook]\n ) {\n self.prestart = prestart\n self.createRuntime = createRuntime\n self.createContainer = createContainer\n self.startContainer = startContainer\n self.poststart = poststart\n self.poststop = poststop\n }\n}\n\npublic struct Linux: Codable, Sendable {\n public var uidMappings: [LinuxIDMapping]\n public var gidMappings: [LinuxIDMapping]\n public var sysctl: [String: String]?\n public var resources: LinuxResources?\n public var cgroupsPath: String\n public var namespaces: [LinuxNamespace]\n public var devices: [LinuxDevice]\n public var seccomp: LinuxSeccomp?\n public var rootfsPropagation: String\n public var maskedPaths: [String]\n public var readonlyPaths: [String]\n public var mountLabel: String\n public var personality: LinuxPersonality?\n\n public init(\n uidMappings: [LinuxIDMapping] = [],\n gidMappings: [LinuxIDMapping] = [],\n sysctl: [String: String]? = nil,\n resources: LinuxResources? = nil,\n cgroupsPath: String = \"\",\n namespaces: [LinuxNamespace] = [],\n devices: [LinuxDevice] = [],\n seccomp: LinuxSeccomp? = nil,\n rootfsPropagation: String = \"\",\n maskedPaths: [String] = [],\n readonlyPaths: [String] = [],\n mountLabel: String = \"\",\n personality: LinuxPersonality? = nil\n ) {\n self.uidMappings = uidMappings\n self.gidMappings = gidMappings\n self.sysctl = sysctl\n self.resources = resources\n self.cgroupsPath = cgroupsPath\n self.namespaces = namespaces\n self.devices = devices\n self.seccomp = seccomp\n self.rootfsPropagation = rootfsPropagation\n self.maskedPaths = maskedPaths\n self.readonlyPaths = readonlyPaths\n self.mountLabel = mountLabel\n self.personality = personality\n }\n}\n\npublic struct LinuxNamespace: Codable, Sendable {\n public var type: LinuxNamespaceType\n public var path: String\n\n public init(type: LinuxNamespaceType, path: String = \"\") {\n self.type = type\n self.path = path\n }\n}\n\npublic enum LinuxNamespaceType: String, Codable, Sendable {\n case pid\n case network\n case uts\n case mount\n case ipc\n case user\n case cgroup\n}\n\npublic struct LinuxIDMapping: Codable, Sendable {\n public var containerID: UInt32\n public var hostID: UInt32\n public var size: UInt32\n\n public init(containerID: UInt32, hostID: UInt32, size: UInt32) {\n self.containerID = containerID\n self.hostID = hostID\n self.size = size\n }\n}\n\npublic struct POSIXRlimit: Codable, Sendable {\n public var type: String\n public var hard: UInt64\n public var soft: UInt64\n\n public init(type: String, hard: UInt64, soft: UInt64) {\n self.type = type\n self.hard = hard\n self.soft = soft\n }\n}\n\npublic struct LinuxHugepageLimit: Codable, Sendable {\n public var pagesize: String\n public var limit: UInt64\n\n public init(pagesize: String, limit: UInt64) {\n self.pagesize = pagesize\n self.limit = limit\n }\n}\n\npublic struct LinuxInterfacePriority: Codable, Sendable {\n public var name: String\n public var priority: UInt32\n\n public init(name: String, priority: UInt32) {\n self.name = name\n self.priority = priority\n }\n}\n\npublic struct LinuxBlockIODevice: Codable, Sendable {\n public var major: Int64\n public var minor: Int64\n\n public init(major: Int64, minor: Int64) {\n self.major = major\n self.minor = minor\n }\n}\n\npublic struct LinuxWeightDevice: Codable, Sendable {\n public var major: Int64\n public var minor: Int64\n public var weight: UInt16?\n public var leafWeight: UInt16?\n\n public init(major: Int64, minor: Int64, weight: UInt16?, leafWeight: UInt16?) {\n self.major = major\n self.minor = minor\n self.weight = weight\n self.leafWeight = leafWeight\n }\n}\n\npublic struct LinuxThrottleDevice: Codable, Sendable {\n public var major: Int64\n public var minor: Int64\n public var rate: UInt64\n\n public init(major: Int64, minor: Int64, rate: UInt64) {\n self.major = major\n self.minor = minor\n self.rate = rate\n }\n}\n\npublic struct LinuxBlockIO: Codable, Sendable {\n public var weight: UInt16?\n public var leafWeight: UInt16?\n public var weightDevice: [LinuxWeightDevice]\n public var throttleReadBpsDevice: [LinuxThrottleDevice]\n public var throttleWriteBpsDevice: [LinuxThrottleDevice]\n public var throttleReadIOPSDevice: [LinuxThrottleDevice]\n public var throttleWriteIOPSDevice: [LinuxThrottleDevice]\n\n public init(\n weight: UInt16?,\n leafWeight: UInt16?,\n weightDevice: [LinuxWeightDevice],\n throttleReadBpsDevice: [LinuxThrottleDevice],\n throttleWriteBpsDevice: [LinuxThrottleDevice],\n throttleReadIOPSDevice: [LinuxThrottleDevice],\n throttleWriteIOPSDevice: [LinuxThrottleDevice]\n ) {\n self.weight = weight\n self.leafWeight = leafWeight\n self.weightDevice = weightDevice\n self.throttleReadBpsDevice = throttleReadBpsDevice\n self.throttleWriteBpsDevice = throttleWriteBpsDevice\n self.throttleReadIOPSDevice = throttleReadIOPSDevice\n self.throttleWriteIOPSDevice = throttleWriteIOPSDevice\n }\n}\n\npublic struct LinuxMemory: Codable, Sendable {\n public var limit: Int64?\n public var reservation: Int64?\n public var swap: Int64?\n public var kernel: Int64?\n public var kernelTCP: Int64?\n public var swappiness: UInt64?\n public var disableOOMKiller: Bool?\n public var useHierarchy: Bool?\n public var checkBeforeUpdate: Bool?\n\n public init(\n limit: Int64? = nil,\n reservation: Int64? = nil,\n swap: Int64? = nil,\n kernel: Int64? = nil,\n kernelTCP: Int64? = nil,\n swappiness: UInt64? = nil,\n disableOOMKiller: Bool? = nil,\n useHierarchy: Bool? = nil,\n checkBeforeUpdate: Bool? = nil\n ) {\n self.limit = limit\n self.reservation = reservation\n self.swap = swap\n self.kernel = kernel\n self.kernelTCP = kernelTCP\n self.swappiness = swappiness\n self.disableOOMKiller = disableOOMKiller\n self.useHierarchy = useHierarchy\n self.checkBeforeUpdate = checkBeforeUpdate\n }\n}\n\npublic struct LinuxCPU: Codable, Sendable {\n public var shares: UInt64?\n public var quota: Int64?\n public var burst: UInt64?\n public var period: UInt64?\n public var realtimeRuntime: Int64?\n public var realtimePeriod: Int64?\n public var cpus: String\n public var mems: String\n public var idle: Int64?\n\n public init(\n shares: UInt64?,\n quota: Int64?,\n burst: UInt64?,\n period: UInt64?,\n realtimeRuntime: Int64?,\n realtimePeriod: Int64?,\n cpus: String,\n mems: String,\n idle: Int64?\n ) {\n self.shares = shares\n self.quota = quota\n self.burst = burst\n self.period = period\n self.realtimeRuntime = realtimeRuntime\n self.realtimePeriod = realtimePeriod\n self.cpus = cpus\n self.mems = mems\n self.idle = idle\n }\n}\n\npublic struct LinuxPids: Codable, Sendable {\n public var limit: Int64\n\n public init(limit: Int64) {\n self.limit = limit\n }\n}\n\npublic struct LinuxNetwork: Codable, Sendable {\n public var classID: UInt32?\n public var priorities: [LinuxInterfacePriority]\n\n public init(classID: UInt32?, priorities: [LinuxInterfacePriority]) {\n self.classID = classID\n self.priorities = priorities\n }\n}\n\npublic struct LinuxRdma: Codable, Sendable {\n public var hcsHandles: UInt32?\n public var hcaObjects: UInt32?\n\n public init(hcsHandles: UInt32?, hcaObjects: UInt32?) {\n self.hcsHandles = hcsHandles\n self.hcaObjects = hcaObjects\n }\n}\n\npublic struct LinuxResources: Codable, Sendable {\n public var devices: [LinuxDeviceCgroup]\n public var memory: LinuxMemory?\n public var cpu: LinuxCPU?\n public var pids: LinuxPids?\n public var blockIO: LinuxBlockIO?\n public var hugepageLimits: [LinuxHugepageLimit]\n public var network: LinuxNetwork?\n public var rdma: [String: LinuxRdma]?\n public var unified: [String: String]?\n\n public init(\n devices: [LinuxDeviceCgroup] = [],\n memory: LinuxMemory? = nil,\n cpu: LinuxCPU? = nil,\n pids: LinuxPids? = nil,\n blockIO: LinuxBlockIO? = nil,\n hugepageLimits: [LinuxHugepageLimit] = [],\n network: LinuxNetwork? = nil,\n rdma: [String: LinuxRdma]? = nil,\n unified: [String: String] = [:]\n ) {\n self.devices = devices\n self.memory = memory\n self.cpu = cpu\n self.pids = pids\n self.blockIO = blockIO\n self.hugepageLimits = hugepageLimits\n self.network = network\n self.rdma = rdma\n self.unified = unified\n }\n}\n\npublic struct LinuxDevice: Codable, Sendable {\n public var path: String\n public var type: String\n public var major: Int64\n public var minor: Int64\n public var fileMode: UInt32?\n public var uid: UInt32?\n public var gid: UInt32?\n\n public init(\n path: String,\n type: String,\n major: Int64,\n minor: Int64,\n fileMode: UInt32?,\n uid: UInt32?,\n gid: UInt32?\n ) {\n self.path = path\n self.type = type\n self.major = major\n self.minor = minor\n self.fileMode = fileMode\n self.uid = uid\n self.gid = gid\n }\n}\n\npublic struct LinuxDeviceCgroup: Codable, Sendable {\n public var allow: Bool\n public var type: String\n public var major: Int64?\n public var minor: Int64?\n public var access: String?\n\n public init(allow: Bool, type: String, major: Int64?, minor: Int64?, access: String?) {\n self.allow = allow\n self.type = type\n self.major = major\n self.minor = minor\n self.access = access\n }\n}\n\npublic enum LinuxPersonalityDomain: String, Codable, Sendable {\n case perLinux = \"LINUX\"\n case perLinux32 = \"LINUX32\"\n}\n\npublic struct LinuxPersonality: Codable, Sendable {\n public var domain: LinuxPersonalityDomain\n public var flags: [String]\n\n public init(domain: LinuxPersonalityDomain, flags: [String]) {\n self.domain = domain\n self.flags = flags\n }\n}\n\npublic struct LinuxSeccomp: Codable, Sendable {\n public var defaultAction: LinuxSeccompAction\n public var defaultErrnoRet: UInt?\n public var architectures: [Arch]\n public var flags: [LinuxSeccompFlag]\n public var listenerPath: String\n public var listenerMetadata: String\n public var syscalls: [LinuxSyscall]\n\n public init(\n defaultAction: LinuxSeccompAction,\n defaultErrnoRet: UInt?,\n architectures: [Arch],\n flags: [LinuxSeccompFlag],\n listenerPath: String,\n listenerMetadata: String,\n syscalls: [LinuxSyscall]\n ) {\n self.defaultAction = defaultAction\n self.defaultErrnoRet = defaultErrnoRet\n self.architectures = architectures\n self.flags = flags\n self.listenerPath = listenerPath\n self.listenerMetadata = listenerMetadata\n self.syscalls = syscalls\n }\n}\n\npublic enum LinuxSeccompFlag: String, Codable, Sendable {\n case flagLog = \"SECCOMP_FILTER_FLAG_LOG\"\n case flagSpecAllow = \"SECCOMP_FILTER_FLAG_SPEC_ALLOW\"\n case flagWaitKillableRecv = \"SECCOMP_FILTER_FLAG_WAIT_KILLABLE_RECV\"\n}\n\npublic enum Arch: String, Codable, Sendable {\n case archX86 = \"SCMP_ARCH_X86\"\n case archX86_64 = \"SCMP_ARCH_X86_64\"\n case archX32 = \"SCMP_ARCH_X32\"\n case archARM = \"SCMP_ARCH_ARM\"\n case archAARCH64 = \"SCMP_ARCH_AARCH64\"\n case archMIPS = \"SCMP_ARCH_MIPS\"\n case archMIPS64 = \"SCMP_ARCH_MIPS64\"\n case archMIPS64N32 = \"SCMP_ARCH_MIPS64N32\"\n case archMIPSEL = \"SCMP_ARCH_MIPSEL\"\n case archMIPSEL64 = \"SCMP_ARCH_MIPSEL64\"\n case archMIPSEL64N32 = \"SCMP_ARCH_MIPSEL64N32\"\n case archPPC = \"SCMP_ARCH_PPC\"\n case archPPC64 = \"SCMP_ARCH_PPC64\"\n case archPPC64LE = \"SCMP_ARCH_PPC64LE\"\n case archS390 = \"SCMP_ARCH_S390\"\n case archS390X = \"SCMP_ARCH_S390X\"\n case archPARISC = \"SCMP_ARCH_PARISC\"\n case archPARISC64 = \"SCMP_ARCH_PARISC64\"\n case archRISCV64 = \"SCMP_ARCH_RISCV64\"\n}\n\npublic enum LinuxSeccompAction: String, Codable, Sendable {\n case actKill = \"SCMP_ACT_KILL\"\n case actKillProcess = \"SCMP_ACT_KILL_PROCESS\"\n case actKillThread = \"SCMP_ACT_KILL_THREAD\"\n case actTrap = \"SCMP_ACT_TRAP\"\n case actErrno = \"SCMP_ACT_ERRNO\"\n case actTrace = \"SCMP_ACT_TRACE\"\n case actAllow = \"SCMP_ACT_ALLOW\"\n case actLog = \"SCMP_ACT_LOG\"\n case actNotify = \"SCMP_ACT_NOTIFY\"\n}\n\npublic enum LinuxSeccompOperator: String, Codable, Sendable {\n case opNotEqual = \"SCMP_CMP_NE\"\n case opLessThan = \"SCMP_CMP_LT\"\n case opLessEqual = \"SCMP_CMP_LE\"\n case opEqualTo = \"SCMP_CMP_EQ\"\n case opGreaterEqual = \"SCMP_CMP_GE\"\n case opGreaterThan = \"SCMP_CMP_GT\"\n case opMaskedEqual = \"SCMP_CMP_MASKED_EQ\"\n}\n\npublic struct LinuxSeccompArg: Codable, Sendable {\n public var index: UInt\n public var value: UInt64\n public var valueTwo: UInt64\n public var op: LinuxSeccompOperator\n\n public init(index: UInt, value: UInt64, valueTwo: UInt64, op: LinuxSeccompOperator) {\n self.index = index\n self.value = value\n self.valueTwo = valueTwo\n self.op = op\n }\n}\n\npublic struct LinuxSyscall: Codable, Sendable {\n public var names: [String]\n public var action: LinuxSeccompAction\n public var errnoRet: UInt?\n public var args: [LinuxSeccompArg]\n\n public init(\n names: [String],\n action: LinuxSeccompAction,\n errnoRet: UInt?,\n args: [LinuxSeccompArg]\n ) {\n self.names = names\n self.action = action\n self.errnoRet = errnoRet\n self.args = args\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Bundle.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\n\n#if canImport(Musl)\nimport Musl\nprivate let _mount = Musl.mount\nprivate let _umount = Musl.umount2\n#elseif canImport(Glibc)\nimport Glibc\nprivate let _mount = Glibc.mount\nprivate let _umount = Glibc.umount2\n#endif\n\n/// `Bundle` represents an OCI runtime spec bundle for running\n/// a container.\npublic struct Bundle: Sendable {\n /// The path to the bundle.\n public let path: URL\n\n /// The path to the OCI runtime spec config.json file.\n public var configPath: URL {\n self.path.appending(path: \"config.json\")\n }\n\n /// The path to a rootfs mount inside the bundle.\n public var rootfsPath: URL {\n self.path.appending(path: \"rootfs\")\n }\n\n /// Create the OCI bundle.\n ///\n /// - Parameters:\n /// - path: A URL pointing to where to create the bundle on the filesystem.\n /// - spec: A data blob that should contain an OCI runtime spec. This will be written\n /// to the bundle as a \"config.json\" file.\n public static func create(path: URL, spec: Data) throws -> Bundle {\n try self.init(path: path, spec: spec)\n }\n\n /// Create the OCI bundle.\n ///\n /// - Parameters:\n /// - path: A URL pointing to where to create the bundle on the filesystem.\n /// - spec: An OCI runtime spec that will be written to the bundle as a \"config.json\"\n /// file.\n public static func create(path: URL, spec: ContainerizationOCI.Spec) throws -> Bundle {\n try self.init(path: path, spec: spec)\n }\n\n /// Load an OCI bundle from the provided path.\n ///\n /// - Parameters:\n /// - path: A URL pointing to where to load the bundle from on the filesystem.\n public static func load(path: URL) throws -> Bundle {\n try self.init(path: path)\n }\n\n private init(path: URL) throws {\n let fm = FileManager.default\n if !fm.fileExists(atPath: path.path) {\n throw ContainerizationError(.invalidArgument, message: \"no bundle at \\(path.path)\")\n }\n self.path = path\n }\n\n // This constructor does not do any validation that data is actually a\n // valid OCI spec.\n private init(path: URL, spec: Data) throws {\n self.path = path\n\n let fm = FileManager.default\n try fm.createDirectory(\n atPath: self.path.appending(component: \"rootfs\").path,\n withIntermediateDirectories: true\n )\n\n try spec.write(to: self.configPath)\n }\n\n private init(path: URL, spec: ContainerizationOCI.Spec) throws {\n self.path = path\n\n let fm = FileManager.default\n try fm.createDirectory(\n atPath: self.path.appending(component: \"rootfs\").path,\n withIntermediateDirectories: true\n )\n\n let specData = try JSONEncoder().encode(spec)\n try specData.write(to: self.configPath)\n }\n\n /// Delete the OCI bundle from the filesystem.\n public func delete() throws {\n // Unmount, and then blow away the dir.\n #if os(Linux)\n let rootfs = self.rootfsPath.path\n guard _umount(rootfs, 0) == 0 else {\n throw POSIXError.fromErrno()\n }\n #endif\n // removeItem is recursive so should blow away the rootfs dir inside as well.\n let fm = FileManager.default\n try fm.removeItem(at: self.path)\n }\n\n /// Load and return the OCI runtime spec written to the bundle.\n public func loadConfig() throws -> ContainerizationOCI.Spec {\n let data = try Data(contentsOf: self.configPath)\n return try JSONDecoder().decode(ContainerizationOCI.Spec.self, from: data)\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/ArchiveWriterConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CArchive\n\n/// Represents the configuration settings for an `ArchiveWriter`.\n///\n/// This struct allows specifying the archive format, compression filter,\n/// various format-specific options, and preferred locales for string encoding.\npublic struct ArchiveWriterConfiguration {\n /// The desired archive format\n public var format: Format\n /// The compression filter to apply to the archive\n public var filter: Filter\n /// An array of format-specific options to apply to the archive.\n /// This includes options like compression level and extended attribute format.\n public var options: [Options]\n /// An array of preferred locale identifiers for string encoding\n public var locales: [String]\n\n /// Initializes a new `ArchiveWriterConfiguration`.\n ///\n /// Sets up the configuration with the specified format, filter, options, and locales.\n public init(\n format: Format, filter: Filter, options: [Options] = [], locales: [String] = [\"en_US.UTF-8\", \"C.UTF-8\"]\n ) {\n self.format = format\n self.filter = filter\n self.options = options\n self.locales = locales\n }\n}\n\nextension ArchiveWriter {\n internal func setFormat(_ format: Format) throws {\n guard let underlying = self.underlying else { throw ArchiveError.noUnderlyingArchive }\n let r = archive_write_set_format(underlying, format.code)\n guard r == ARCHIVE_OK else { throw ArchiveError.unableToSetFormat(r, format) }\n }\n\n internal func addFilter(_ filter: Filter) throws {\n guard let underlying = self.underlying else { throw ArchiveError.noUnderlyingArchive }\n let r = archive_write_add_filter(underlying, filter.code)\n guard r == ARCHIVE_OK else { throw ArchiveError.unableToAddFilter(r, filter) }\n }\n\n internal func setOptions(_ options: [Options]) throws {\n try options.forEach {\n switch $0 {\n case .compressionLevel(let level):\n try wrap(\n archive_write_set_option(underlying, nil, \"compression-level\", \"\\(level)\"),\n ArchiveError.unableToSetOption, underlying: self.underlying)\n case .compression(.store):\n try wrap(\n archive_write_set_option(underlying, nil, \"compression\", \"store\"), ArchiveError.unableToSetOption,\n underlying: self.underlying)\n case .compression(.deflate):\n try wrap(\n archive_write_set_option(underlying, nil, \"compression\", \"deflate\"), ArchiveError.unableToSetOption,\n underlying: self.underlying)\n case .xattrformat(let value):\n let v = value.description\n try wrap(\n archive_write_set_option(underlying, nil, \"xattrheader\", v), ArchiveError.unableToSetOption,\n underlying: self.underlying)\n }\n }\n }\n}\n\npublic enum Options {\n case compressionLevel(UInt32)\n case compression(Compression)\n case xattrformat(XattrFormat)\n\n public enum Compression {\n case store\n case deflate\n }\n\n public enum XattrFormat: String, CustomStringConvertible {\n case schily\n case libarchive\n case all\n\n public var description: String {\n switch self {\n case .libarchive:\n return \"LIBARCHIVE\"\n case .schily:\n return \"SCHILY\"\n case .all:\n return \"ALL\"\n }\n }\n }\n}\n\n/// An enumeration of the supported archive formats.\npublic enum Format: String, Sendable {\n /// POSIX-standard `ustar` archives\n case ustar\n case gnutar\n /// POSIX `pax interchange format` archives\n case pax\n case paxRestricted\n /// POSIX octet-oriented cpio archives\n case cpio\n case cpioNewc\n /// Zip archive\n case zip\n /// two different variants of shar archives\n case shar\n case sharDump\n /// ISO9660 CD images\n case iso9660\n /// 7-Zip archives\n case sevenZip\n /// ar archives\n case arBSD\n case arGNU\n /// mtree file tree descriptions\n case mtree\n /// XAR archives\n case xar\n\n internal var code: CInt {\n switch self {\n case .ustar: return ARCHIVE_FORMAT_TAR_USTAR\n case .pax: return ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE\n case .paxRestricted: return ARCHIVE_FORMAT_TAR_PAX_RESTRICTED\n case .gnutar: return ARCHIVE_FORMAT_TAR_GNUTAR\n case .cpio: return ARCHIVE_FORMAT_CPIO_POSIX\n case .cpioNewc: return ARCHIVE_FORMAT_CPIO_AFIO_LARGE\n case .zip: return ARCHIVE_FORMAT_ZIP\n case .shar: return ARCHIVE_FORMAT_SHAR_BASE\n case .sharDump: return ARCHIVE_FORMAT_SHAR_DUMP\n case .iso9660: return ARCHIVE_FORMAT_ISO9660\n case .sevenZip: return ARCHIVE_FORMAT_7ZIP\n case .arBSD: return ARCHIVE_FORMAT_AR_BSD\n case .arGNU: return ARCHIVE_FORMAT_AR_GNU\n case .mtree: return ARCHIVE_FORMAT_MTREE\n case .xar: return ARCHIVE_FORMAT_XAR\n }\n }\n}\n\n/// An enumeration of the supported filters (compression / encoding standards) for an archive.\npublic enum Filter: String, Sendable {\n case none\n case gzip\n case bzip2\n case compress\n case lzma\n case xz\n case uu\n case rpm\n case lzip\n case lrzip\n case lzop\n case grzip\n case lz4\n\n internal var code: CInt {\n switch self {\n case .none: return ARCHIVE_FILTER_NONE\n case .gzip: return ARCHIVE_FILTER_GZIP\n case .bzip2: return ARCHIVE_FILTER_BZIP2\n case .compress: return ARCHIVE_FILTER_COMPRESS\n case .lzma: return ARCHIVE_FILTER_LZMA\n case .xz: return ARCHIVE_FILTER_XZ\n case .uu: return ARCHIVE_FILTER_UU\n case .rpm: return ARCHIVE_FILTER_RPM\n case .lzip: return ARCHIVE_FILTER_LZIP\n case .lrzip: return ARCHIVE_FILTER_LRZIP\n case .lzop: return ARCHIVE_FILTER_LZOP\n case .grzip: return ARCHIVE_FILTER_GRZIP\n case .lz4: return ARCHIVE_FILTER_LZ4\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/CIDRAddress.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Describes an IPv4 CIDR address block.\npublic struct CIDRAddress: CustomStringConvertible, Equatable, Sendable {\n\n /// The base IPv4 address of the CIDR block.\n public let lower: IPv4Address\n\n /// The last IPv4 address of the CIDR block\n public let upper: IPv4Address\n\n /// The IPv4 address component of the CIDR block.\n public let address: IPv4Address\n\n /// The address prefix length for the CIDR block, which determines its size.\n public let prefixLength: PrefixLength\n\n /// Create an CIDR address block from its text representation.\n public init(_ cidr: String) throws {\n let split = cidr.components(separatedBy: \"/\")\n guard split.count == 2 else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n address = try IPv4Address(split[0])\n guard let prefixLength = PrefixLength(split[1]) else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n guard prefixLength >= 0 && prefixLength <= 32 else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n\n self.prefixLength = prefixLength\n lower = address.prefix(prefixLength: prefixLength)\n upper = IPv4Address(fromValue: lower.value + prefixLength.suffixMask32)\n }\n\n /// Create a CIDR address from a member IP and a prefix length.\n public init(_ address: IPv4Address, prefixLength: PrefixLength) throws {\n guard prefixLength >= 0 && prefixLength <= 32 else {\n throw NetworkAddressError.invalidCIDR(cidr: \"\\(address)/\\(prefixLength)\")\n }\n\n self.prefixLength = prefixLength\n self.address = address\n lower = address.prefix(prefixLength: prefixLength)\n upper = IPv4Address(fromValue: lower.value + prefixLength.suffixMask32)\n }\n\n /// Create the smallest CIDR block that includes the lower and upper bounds.\n public init(lower: IPv4Address, upper: IPv4Address) throws {\n guard lower.value <= upper.value else {\n throw NetworkAddressError.invalidAddressRange(lower: lower.description, upper: upper.description)\n }\n\n address = lower\n for prefixLength: PrefixLength in 1...32 {\n // find the first case where a subnet mask would put lower and upper in different CIDR block\n let mask = prefixLength.prefixMask32\n\n if (lower.value & mask) != (upper.value & mask) {\n self.prefixLength = prefixLength - 1\n self.lower = address.prefix(prefixLength: self.prefixLength)\n self.upper = IPv4Address(fromValue: self.lower.value + self.prefixLength.suffixMask32)\n return\n }\n }\n\n // if lower and upper are same, create a /32 block\n self.prefixLength = 32\n self.lower = lower\n self.upper = upper\n }\n\n /// Get the offset of the specified address, relative to the\n /// base address for the CIDR block, returning nil if the block\n /// does not contain the address.\n public func getIndex(_ address: IPv4Address) -> UInt32? {\n guard address.value >= lower.value && address.value <= upper.value else {\n return nil\n }\n\n return address.value - lower.value\n }\n\n /// Return true if the CIDR block contains the specified address.\n public func contains(ipv4: IPv4Address) -> Bool {\n lower.value <= ipv4.value && ipv4.value <= upper.value\n }\n\n /// Return true if the CIDR block contains all addresses of another CIDR block.\n public func contains(cidr: CIDRAddress) -> Bool {\n lower.value <= cidr.lower.value && cidr.upper.value <= upper.value\n }\n\n /// Return true if the CIDR block shares any addresses with another CIDR block.\n public func overlaps(cidr: CIDRAddress) -> Bool {\n (lower.value <= cidr.lower.value && upper.value >= cidr.lower.value)\n || (upper.value >= cidr.upper.value && lower.value <= cidr.upper.value)\n }\n\n /// Retrieve the text representation of the CIDR block.\n public var description: String {\n \"\\(address)/\\(prefixLength)\"\n }\n}\n\nextension CIDRAddress: Codable {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n let text = try container.decode(String.self)\n try self.init(text)\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n try container.encode(self.description)\n }\n}\n"], ["/containerization/Sources/Containerization/HostsConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Static table lookups for a container. The values will be used to\n/// construct /etc/hosts for a given container.\npublic struct Hosts: Sendable {\n /// Represents one entry in an /etc/hosts file.\n public struct Entry: Sendable {\n /// The IPV4 or IPV6 address in String form.\n public var ipAddress: String\n /// The hostname(s) for the entry.\n public var hostnames: [String]\n /// An optional comment to be placed to the right side of the entry.\n public var comment: String?\n\n public init(ipAddress: String, hostnames: [String], comment: String? = nil) {\n self.comment = comment\n self.hostnames = hostnames\n self.ipAddress = ipAddress\n }\n\n /// The information in the structure rendered to a String representation\n /// that matches the format /etc/hosts expects.\n public var rendered: String {\n var line = ipAddress\n if !hostnames.isEmpty {\n line += \" \" + hostnames.joined(separator: \" \")\n }\n if let comment {\n line += \" # \\(comment) \"\n }\n return line\n }\n\n public static func localHostIPV4(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"127.0.0.1\",\n hostnames: [\"localhost\"],\n comment: comment\n )\n }\n\n public static func localHostIPV6(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"::1\",\n hostnames: [\"localhost\", \"ip6-localhost\", \"ip6-loopback\"],\n comment: comment\n )\n }\n\n public static func ipv6LocalNet(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"fe00::\",\n hostnames: [\"ip6-localnet\"],\n comment: comment\n )\n }\n\n public static func ipv6MulticastPrefix(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"ff00::\",\n hostnames: [\"ip6-mcastprefix\"],\n comment: comment\n )\n }\n\n public static func ipv6AllNodes(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"ff02::1\",\n hostnames: [\"ip6-allnodes\"],\n comment: comment\n )\n }\n\n public static func ipv6AllRouters(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"ff02::2\",\n hostnames: [\"ip6-allrouters\"],\n comment: comment\n )\n }\n }\n\n /// The entries to be written to /etc/hosts.\n public var entries: [Entry]\n\n /// A comment to render at the top of the file.\n public var comment: String?\n\n public init(\n entries: [Entry],\n comment: String? = nil\n ) {\n self.entries = entries\n self.comment = comment\n }\n}\n\nextension Hosts {\n /// A default entry that can be used for convenience. It contains a IPV4\n /// and IPV6 localhost entry, as well as ipv6 localnet, ipv6 mcastprefix,\n /// ipv6 allnodes, and ipv6 allrouters.\n public static let `default` = Hosts(entries: [\n Entry.localHostIPV4(),\n Entry.localHostIPV6(),\n Entry.ipv6LocalNet(),\n Entry.ipv6MulticastPrefix(),\n Entry.ipv6AllNodes(),\n Entry.ipv6AllRouters(),\n ])\n\n /// Returns a string variant of the data that can be written to\n /// /etc/hosts directly.\n public var hostsFile: String {\n var lines: [String] = []\n\n if let comment {\n lines.append(\"# \\(comment)\")\n }\n\n for entry in entries {\n lines.append(entry.rendered)\n }\n\n return lines.joined(separator: \"\\n\") + \"\\n\"\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Linux/Binfmt.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n#if canImport(Musl)\nimport Musl\nprivate let _mount = Musl.mount\n#elseif canImport(Glibc)\nimport Glibc\nprivate let _mount = Glibc.mount\n#endif\n\n/// `Binfmt` is a utility type that contains static helpers and types for\n/// mounting the Linux binfmt_misc filesystem, and creating new binfmt entries.\npublic struct Binfmt: Sendable {\n /// Default mount path for binfmt_misc.\n public static let path = \"/proc/sys/fs/binfmt_misc\"\n\n /// Entry models a binfmt_misc entry.\n /// https://docs.kernel.org/admin-guide/binfmt-misc.html\n public struct Entry {\n public var name: String\n public var type: String\n public var offset: String\n public var magic: String\n public var mask: String\n public var flags: String\n\n public init(\n name: String,\n type: String = \"M\",\n offset: String = \"\",\n magic: String,\n mask: String,\n flags: String = \"CF\"\n ) {\n self.name = name\n self.type = type\n self.offset = offset\n self.magic = magic\n self.mask = mask\n self.flags = flags\n }\n\n /// Returns a binfmt `Entry` for amd64 ELF binaries.\n public static func amd64() -> Self {\n Binfmt.Entry(\n name: \"x86_64\",\n magic: #\"\\x7fELF\\x02\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x3e\\x00\"#,\n mask: #\"\\xff\\xff\\xff\\xff\\xff\\xfe\\xfe\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff\"#\n )\n }\n\n #if os(Linux)\n /// Register the passed in `binaryPath` as the interpreter for a new binfmt_misc entry.\n public func register(binaryPath: String) throws {\n let registration = \":\\(self.name):\\(self.type):\\(self.offset):\\(self.magic):\\(self.mask):\\(binaryPath):\\(self.flags)\"\n\n try registration.write(\n to: URL(fileURLWithPath: Binfmt.path).appendingPathComponent(\"register\"),\n atomically: false,\n encoding: .ascii\n )\n }\n\n /// Deregister the binfmt_misc entry described by the current object.\n public func deregister() throws {\n let data = \"-1\"\n try data.write(\n to: URL(fileURLWithPath: Binfmt.path).appendingPathComponent(self.name),\n atomically: false,\n encoding: .ascii\n )\n }\n #endif // os(Linux)\n }\n\n #if os(Linux)\n /// Crude check to see if /proc/sys/fs/binfmt_misc/register exists.\n public static func mounted() -> Bool {\n FileManager.default.fileExists(atPath: \"\\(Self.path)/register\")\n }\n\n /// Mount the binfmt_misc filesystem.\n public static func mount() throws {\n guard _mount(\"binfmt_misc\", Self.path, \"binfmt_misc\", 0, \"\") == 0 else {\n throw POSIXError.fromErrno()\n }\n }\n #endif // os(Linux)\n}\n"], ["/containerization/Sources/ContainerizationEXT4/FilePath+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\nextension FilePath {\n public static let Separator: String = \"/\"\n\n public var bytes: [UInt8] {\n self.withCString { cstr in\n var ptr = cstr\n var rawBytes: [UInt8] = []\n while UInt(bitPattern: ptr) != 0 {\n if ptr.pointee == 0x00 { break }\n rawBytes.append(UInt8(bitPattern: ptr.pointee))\n ptr = ptr.successor()\n }\n return rawBytes\n }\n }\n\n public var base: String {\n self.lastComponent?.string ?? \"/\"\n }\n\n public var dir: FilePath {\n self.removingLastComponent()\n }\n\n public var url: URL {\n URL(fileURLWithPath: self.string)\n }\n\n public var items: [String] {\n self.components.map { $0.string }\n }\n\n public init(_ url: URL) {\n self.init(url.path(percentEncoded: false))\n }\n\n public init?(_ data: Data) {\n let cstr: String? = data.withUnsafeBytes { (rbp: UnsafeRawBufferPointer) in\n guard let baseAddress = rbp.baseAddress else {\n return nil\n }\n\n let cString = baseAddress.bindMemory(to: CChar.self, capacity: data.count)\n return String(cString: cString)\n }\n\n guard let cstr else {\n return nil\n }\n self.init(cstr)\n }\n\n public func join(_ path: FilePath) -> FilePath {\n self.pushing(path)\n }\n\n public func join(_ path: String) -> FilePath {\n self.join(FilePath(path))\n }\n\n public func split() -> (dir: FilePath, base: String) {\n (self.dir, self.base)\n }\n\n public func clean() -> FilePath {\n self.lexicallyNormalized()\n }\n\n public static func rel(_ basepath: String, _ targpath: String) -> FilePath {\n let base = FilePath(basepath)\n let targ = FilePath(targpath)\n\n if base == targ {\n return \".\"\n }\n\n let baseComponents = base.items\n let targComponents = targ.items\n\n var commonPrefix = 0\n while commonPrefix < min(baseComponents.count, targComponents.count)\n && baseComponents[commonPrefix] == targComponents[commonPrefix]\n {\n commonPrefix += 1\n }\n\n let upCount = baseComponents.count - commonPrefix\n let relComponents = Array(repeating: \"..\", count: upCount) + targComponents[commonPrefix...]\n\n return FilePath(relComponents.joined(separator: Self.Separator))\n }\n}\n\nextension FileHandle {\n public convenience init?(forWritingTo path: FilePath) {\n self.init(forWritingAtPath: path.description)\n }\n\n public convenience init?(forReadingAtPath path: FilePath) {\n self.init(forReadingAtPath: path.description)\n }\n\n public convenience init?(forReadingFrom path: FilePath) {\n self.init(forReadingAtPath: path.description)\n }\n}\n"], ["/containerization/Sources/Containerization/VsockConnectionStream.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n#if os(macOS)\nimport Virtualization\n#endif\n\n/// A stream of vsock connections.\npublic final class VsockConnectionStream: NSObject, Sendable {\n /// A stream of connections dialed from the remote.\n public let connections: AsyncStream\n /// The port the connections are for.\n public let port: UInt32\n\n private let cont: AsyncStream.Continuation\n\n public init(port: UInt32) {\n self.port = port\n let (stream, continuation) = AsyncStream.makeStream(of: FileHandle.self)\n self.connections = stream\n self.cont = continuation\n }\n\n public func finish() {\n self.cont.finish()\n }\n}\n\n#if os(macOS)\n\nextension VsockConnectionStream: VZVirtioSocketListenerDelegate {\n public func listener(\n _: VZVirtioSocketListener, shouldAcceptNewConnection conn: VZVirtioSocketConnection,\n from _: VZVirtioSocketDevice\n ) -> Bool {\n let fd = dup(conn.fileDescriptor)\n conn.close()\n\n cont.yield(FileHandle(fileDescriptor: fd, closeOnDealloc: false))\n return true\n }\n}\n\n#endif\n"], ["/containerization/Sources/ContainerizationExtras/AsyncLock.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// `AsyncLock` provides a familiar locking API, with the main benefit being that it\n/// is safe to call async methods while holding the lock. This is primarily used in spots\n/// where an actor makes sense, but we may need to ensure we don't fall victim to actor\n/// reentrancy issues.\npublic actor AsyncLock {\n private var busy = false\n private var queue: ArraySlice> = []\n\n public struct Context: Sendable {\n fileprivate init() {}\n }\n\n public init() {}\n\n /// withLock provides a scoped locking API to run a function while holding the lock.\n public func withLock(_ body: @Sendable @escaping (Context) async throws -> T) async rethrows -> T {\n while self.busy {\n await withCheckedContinuation { cc in\n self.queue.append(cc)\n }\n }\n\n self.busy = true\n\n defer {\n self.busy = false\n if let next = self.queue.popFirst() {\n next.resume(returning: ())\n } else {\n self.queue = []\n }\n }\n\n let context = Context()\n return try await body(context)\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/Timeout.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// `Timeout` contains helpers to run an operation and error out if\n/// the operation does not finish within a provided time.\npublic struct Timeout {\n /// Performs the passed in `operation` and throws a `CancellationError` if the operation\n /// doesn't finish in the provided `seconds` amount.\n public static func run(\n seconds: UInt32,\n operation: @escaping @Sendable () async -> T\n ) async throws -> T {\n try await withThrowingTaskGroup(of: T.self) { group in\n group.addTask {\n await operation()\n }\n\n group.addTask {\n try await Task.sleep(for: .seconds(seconds))\n throw CancellationError()\n }\n\n guard let result = try await group.next() else {\n fatalError()\n }\n\n group.cancelAll()\n return result\n }\n }\n}\n"], ["/containerization/Sources/Containerization/Image/InitImage.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\n/// Data representing the image to use as the root filesystem for a virtual machine.\n/// Typically this image would contain the guest agent used to facilitate container\n/// workloads, as well as any extras that may be useful to have in the guest.\npublic struct InitImage: Sendable {\n public var name: String { image.reference }\n\n let image: Image\n\n public init(image: Image) {\n self.image = image\n }\n}\n\nextension InitImage {\n /// Unpack the initial filesystem for the desired platform at a given path.\n public func initBlock(at: URL, for platform: SystemPlatform) async throws -> Mount {\n let unpacker = EXT4Unpacker(blockSizeInBytes: 512.mib())\n var fs = try await unpacker.unpack(self.image, for: platform.ociPlatform(), at: at)\n fs.options = [\"ro\"]\n return fs\n }\n\n /// Create a new InitImage with the reference as the name.\n /// The `rootfs` parameter must be a tar.gz file whose contents make up the filesystem for the image.\n public static func create(\n reference: String, rootfs: URL, platform: Platform,\n labels: [String: String] = [:], imageStore: ImageStore, contentStore: ContentStore\n ) async throws -> InitImage {\n\n let indexDescriptorStore = AsyncStore()\n try await contentStore.ingest { dir in\n let writer = try ContentWriter(for: dir)\n var result = try writer.create(from: rootfs)\n let layerDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.imageLayerGzip, digest: result.digest.digestString, size: result.size)\n\n // TODO: compute and fill in the correct diffID for the above layer\n // We currently put in the sha of the fully compressed layer, this needs to be replaced with\n // the sha of the uncompressed layer.\n let rootfsConfig = ContainerizationOCI.Rootfs(type: \"layers\", diffIDs: [result.digest.digestString])\n let runtimeConfig = ContainerizationOCI.ImageConfig(labels: labels)\n let imageConfig = ContainerizationOCI.Image(architecture: platform.architecture, os: platform.os, config: runtimeConfig, rootfs: rootfsConfig)\n result = try writer.create(from: imageConfig)\n let configDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.imageConfig, digest: result.digest.digestString, size: result.size)\n\n let manifest = Manifest(config: configDescriptor, layers: [layerDescriptor])\n result = try writer.create(from: manifest)\n let manifestDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.imageManifest, digest: result.digest.digestString, size: result.size, platform: platform)\n\n let index = ContainerizationOCI.Index(manifests: [manifestDescriptor])\n result = try writer.create(from: index)\n\n let indexDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.index, digest: result.digest.digestString, size: result.size)\n await indexDescriptorStore.set(indexDescriptor)\n\n }\n\n guard let indexDescriptor = await indexDescriptorStore.get() else {\n throw ContainerizationError(.notFound, message: \"image for \\(reference) not found\")\n }\n\n let description = Image.Description(reference: reference, descriptor: indexDescriptor)\n let image = try await imageStore.create(description: description)\n return InitImage(image: image)\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/NetworkAddress+Allocator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension IPv4Address {\n /// Creates an allocator for IPv4 addresses.\n public static func allocator(lower: UInt32, size: Int) throws -> any AddressAllocator {\n // NOTE: 2^31 - 1 size limit in the very improbable case that we run on 32-bit.\n guard size > 0 && size < Int.max && 0xffff_ffff - lower >= size - 1 else {\n throw AllocatorError.rangeExceeded\n }\n return IndexedAddressAllocator(\n size: size,\n addressToIndex: { address in\n guard address.value >= lower && address.value - lower <= UInt32(size) else {\n return nil\n }\n return Int(address.value - lower)\n },\n indexToAddress: { IPv4Address(fromValue: lower + UInt32($0)) }\n )\n }\n}\n\nextension UInt16 {\n /// Creates an allocator for TCP/UDP ports and other UInt16 values.\n public static func allocator(lower: UInt16, size: Int) throws -> any AddressAllocator {\n guard 0xffff - lower + 1 >= size else {\n throw AllocatorError.rangeExceeded\n }\n\n return IndexedAddressAllocator(\n size: size,\n addressToIndex: { address in\n guard address >= lower && address <= lower + UInt16(size) else {\n return nil\n }\n return Int(address - lower)\n },\n indexToAddress: { lower + UInt16($0) }\n )\n }\n}\n\nextension UInt32 {\n /// Creates an allocator for vsock ports, or any UInt32 values.\n public static func allocator(lower: UInt32, size: Int) throws -> any AddressAllocator {\n guard 0xffff_ffff - lower + 1 >= size else {\n throw AllocatorError.rangeExceeded\n }\n\n return IndexedAddressAllocator(\n size: size,\n addressToIndex: { address in\n guard address >= lower && address <= lower + UInt32(size) else {\n return nil\n }\n return Int(address - lower)\n },\n indexToAddress: { lower + UInt32($0) }\n )\n }\n\n /// Creates a rotating allocator for vsock ports, or any UInt32 values.\n public static func rotatingAllocator(lower: UInt32, size: UInt32) throws -> any AddressAllocator {\n guard 0xffff_ffff - lower + 1 >= size else {\n throw AllocatorError.rangeExceeded\n }\n\n return RotatingAddressAllocator(\n size: size,\n addressToIndex: { address in\n guard address >= lower && address <= lower + UInt32(size) else {\n return nil\n }\n return Int(address - lower)\n },\n indexToAddress: { lower + UInt32($0) }\n )\n }\n}\n\nextension Character {\n private static let deviceLetters = Array(\"abcdefghijklmnopqrstuvwxyz\")\n\n /// Creates an allocator for block device tags, or any character values.\n public static func blockDeviceTagAllocator() -> any AddressAllocator {\n IndexedAddressAllocator(\n size: Self.deviceLetters.count,\n addressToIndex: { address in\n Self.deviceLetters.firstIndex(of: address)\n },\n indexToAddress: { Self.deviceLetters[$0] }\n )\n }\n}\n"], ["/containerization/Sources/SendablePropertyMacros/SendablePropertyMacroUnchecked.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SwiftCompilerPlugin\nimport SwiftParser\nimport SwiftSyntax\nimport SwiftSyntaxBuilder\nimport SwiftSyntaxMacros\n\n/// A macro that allows to make a property of a custom type thread-safe keeping the `Sendable` conformance of the type. This macro can be used with classes and enums. Avoid using it with structs, arrays, and dictionaries.\npublic struct SendablePropertyMacroUnchecked: PeerMacro {\n private static func peerPropertyName(for propertyName: String) -> String {\n \"_\" + propertyName\n }\n\n /// The macro expansion that introduces a `Sendable`-conforming \"peer\" declaration for a thread-safe storage for the value of the given declaration of a variable.\n /// - Parameters:\n /// - node: The given attribute node.\n /// - declaration: The given declaration.\n /// - context: The macro expansion context.\n public static func expansion(\n of node: SwiftSyntax.AttributeSyntax, providingPeersOf declaration: some SwiftSyntax.DeclSyntaxProtocol, in context: some SwiftSyntaxMacros.MacroExpansionContext\n ) throws -> [SwiftSyntax.DeclSyntax] {\n guard let varDecl = declaration.as(VariableDeclSyntax.self),\n let binding = varDecl.bindings.first,\n let pattern = binding.pattern.as(IdentifierPatternSyntax.self)\n else {\n throw SendablePropertyError.onlyApplicableToVar\n }\n\n let propertyName = pattern.identifier.text\n let hasInitializer = binding.initializer != nil\n let initializerValue = binding.initializer?.value.description ?? \"nil\"\n\n var genericTypeAnnotation = \"\"\n if let typeAnnotation = binding.typeAnnotation {\n let typeName = typeAnnotation.type.description.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)\n genericTypeAnnotation = \"<\\(typeName)\\(hasInitializer ? \"\" : \"?\")>\"\n }\n\n let accessLevel = varDecl.modifiers.first(where: { [\"open\", \"public\", \"internal\", \"fileprivate\", \"private\"].contains($0.name.text) })?.name.text ?? \"internal\"\n\n // Create a peer property\n let peerPropertyName = self.peerPropertyName(for: propertyName)\n let peerProperty: DeclSyntax =\n \"\"\"\n \\(raw: accessLevel) let \\(raw: peerPropertyName) = Synchronized\\(raw: genericTypeAnnotation)(\\(raw: initializerValue))\n \"\"\"\n return [peerProperty]\n }\n}\n\nextension SendablePropertyMacroUnchecked: AccessorMacro {\n /// The macro expansion that adds `Sendable`-conforming accessors to the given declaration of a variable.\n /// - Parameters:\n /// - node: The given attribute node.\n /// - declaration: The given declaration.\n /// - context: The macro expansion context.\n public static func expansion(\n of node: SwiftSyntax.AttributeSyntax, providingAccessorsOf declaration: some SwiftSyntax.DeclSyntaxProtocol, in context: some SwiftSyntaxMacros.MacroExpansionContext\n ) throws -> [SwiftSyntax.AccessorDeclSyntax] {\n guard let varDecl = declaration.as(VariableDeclSyntax.self),\n let binding = varDecl.bindings.first,\n let pattern = binding.pattern.as(IdentifierPatternSyntax.self)\n else {\n throw SendablePropertyError.onlyApplicableToVar\n }\n\n let propertyName = pattern.identifier.text\n let hasInitializer = binding.initializer != nil\n\n // Replace the property with an accessor\n let peerPropertyName = Self.peerPropertyName(for: propertyName)\n\n let accessorGetter: AccessorDeclSyntax =\n \"\"\"\n get {\n \\(raw: peerPropertyName).withLock { $0\\(raw: hasInitializer ? \"\" : \"!\") }\n }\n \"\"\"\n let accessorSetter: AccessorDeclSyntax =\n \"\"\"\n set {\n \\(raw: peerPropertyName).withLock { $0 = newValue }\n }\n \"\"\"\n\n return [accessorGetter, accessorSetter]\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/LocalContent.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Crypto\nimport Foundation\n\npublic final class LocalContent: Content {\n public let path: URL\n private let file: FileHandle\n\n public init(path: URL) throws {\n guard FileManager.default.fileExists(atPath: path.path) else {\n throw ContainerizationError(.notFound, message: \"Content at path \\(path.absolutePath())\")\n }\n\n self.file = try FileHandle(forReadingFrom: path)\n self.path = path\n }\n\n public func digest() throws -> SHA256.Digest {\n let bufferSize = 64 * 1024 // 64 KB\n var hasher = SHA256()\n\n try self.file.seek(toOffset: 0)\n while case let data = file.readData(ofLength: bufferSize), !data.isEmpty {\n hasher.update(data: data)\n }\n\n let digest = hasher.finalize()\n\n try self.file.seek(toOffset: 0)\n return digest\n }\n\n public func data(offset: UInt64 = 0, length size: Int = 0) throws -> Data? {\n try file.seek(toOffset: offset)\n if size == 0 {\n return try file.readToEnd()\n }\n return try file.read(upToCount: size)\n }\n\n public func data() throws -> Data {\n try Data(contentsOf: self.path)\n }\n\n public func size() throws -> UInt64 {\n let fileAttrs = try FileManager.default.attributesOfItem(atPath: self.path.absolutePath())\n if let size = fileAttrs[FileAttributeKey.size] as? UInt64 {\n return size\n }\n throw ContainerizationError(.internalError, message: \"Could not determine file size for \\(path.absolutePath())\")\n }\n\n public func decode() throws -> T where T: Decodable {\n let json = JSONDecoder()\n let data = try Data(contentsOf: self.path)\n return try json.decode(T.self, from: data)\n }\n\n deinit {\n try? self.file.close()\n }\n}\n"], ["/containerization/Sources/cctl/cctl+Utils.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\nextension Application {\n static func fetchImage(reference: String, store: ImageStore) async throws -> Containerization.Image {\n do {\n return try await store.get(reference: reference)\n } catch let error as ContainerizationError {\n if error.code == .notFound {\n return try await store.pull(reference: reference)\n }\n throw error\n }\n }\n\n static func parseKeyValuePairs(from items: [String]) -> [String: String] {\n var parsedLabels: [String: String] = [:]\n for item in items {\n let parts = item.split(separator: \"=\", maxSplits: 1)\n guard parts.count == 2 else {\n continue\n }\n let key = String(parts[0])\n let val = String(parts[1])\n parsedLabels[key] = val\n }\n return parsedLabels\n }\n}\n\nextension ContainerizationOCI.Platform {\n static var arm64: ContainerizationOCI.Platform {\n .init(arch: \"arm64\", os: \"linux\", variant: \"v8\")\n }\n}\n"], ["/containerization/Sources/Containerization/Agent/Vminitd+Rosetta.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\n\nextension Vminitd {\n /// Enable Rosetta's x86_64 emulation.\n public func enableRosetta() async throws {\n let path = \"/run/rosetta\"\n try await self.mount(\n .init(\n type: \"virtiofs\",\n source: \"rosetta\",\n destination: path\n )\n )\n try await self.setupEmulator(\n binaryPath: \"\\(path)/rosetta\",\n configuration: Binfmt.Entry.amd64()\n )\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/IPAddress.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Facilitates conversion between IPv4 address representations.\npublic struct IPv4Address: Codable, CustomStringConvertible, Equatable, Sendable {\n /// The address as a 32-bit integer.\n public let value: UInt32\n\n /// Create an address from a dotted-decimal string, such as \"192.168.64.10\".\n public init(_ fromString: String) throws {\n let split = fromString.components(separatedBy: \".\")\n if split.count != 4 {\n throw NetworkAddressError.invalidStringAddress(address: fromString)\n }\n\n var parsedValue: UInt32 = 0\n for index in 0..<4 {\n guard let octet = UInt8(split[index]) else {\n throw NetworkAddressError.invalidStringAddress(address: fromString)\n }\n parsedValue |= UInt32(octet) << ((3 - index) * 8)\n }\n\n value = parsedValue\n }\n\n /// Create an address from an array of four bytes in network order (big-endian),\n /// such as [192, 168, 64, 10].\n public init(fromNetworkBytes: [UInt8]) throws {\n guard fromNetworkBytes.count == 4 else {\n throw NetworkAddressError.invalidNetworkByteAddress(address: fromNetworkBytes)\n }\n\n value =\n (UInt32(fromNetworkBytes[0]) << 24)\n | (UInt32(fromNetworkBytes[1]) << 16)\n | (UInt32(fromNetworkBytes[2]) << 8)\n | UInt32(fromNetworkBytes[3])\n }\n\n /// Create an address from a 32-bit integer, such as 0xc0a8_400a.\n public init(fromValue: UInt32) {\n value = fromValue\n }\n\n /// Retrieve the address as an array of bytes in network byte order.\n public var networkBytes: [UInt8] {\n [\n UInt8((value >> 24) & 0xff),\n UInt8((value >> 16) & 0xff),\n UInt8((value >> 8) & 0xff),\n UInt8(value & 0xff),\n ]\n }\n\n /// Retrieve the address as a dotted decimal string.\n public var description: String {\n networkBytes.map(String.init).joined(separator: \".\")\n }\n\n /// Create the base IPv4 address for a network that contains this\n /// address and uses the specified subnet mask length.\n public func prefix(prefixLength: PrefixLength) -> IPv4Address {\n IPv4Address(fromValue: value & prefixLength.prefixMask32)\n }\n}\n\nextension IPv4Address {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n let text = try container.decode(String.self)\n try self.init(text)\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n try container.encode(self.description)\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Path.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// `Path` provides utilities to look for binaries in the current PATH,\n/// or to return the current PATH.\npublic struct Path {\n /// lookPath looks up an executable's path from $PATH\n public static func lookPath(_ name: String) -> URL? {\n lookup(name, path: getPath())\n }\n\n // getEnv returns the default environment of the process\n // with the default $PATH added for the context of a macOS application bundle\n public static func getEnv() -> [String: String] {\n var env = ProcessInfo.processInfo.environment\n env[\"PATH\"] = getPath()\n return env\n }\n\n private static func lookup(_ name: String, path: String) -> URL? {\n if name.contains(\"/\") {\n if findExec(name) {\n return URL(fileURLWithPath: name)\n }\n return nil\n }\n\n for var lookdir in path.split(separator: \":\") {\n if lookdir.isEmpty {\n lookdir = \".\"\n }\n let file = URL(fileURLWithPath: String(lookdir)).appendingPathComponent(name)\n if findExec(file.path) {\n return file\n }\n }\n return nil\n }\n\n /// getPath returns $PATH for the current process\n private static func getPath() -> String {\n let env = ProcessInfo.processInfo.environment\n return env[\"PATH\"] ?? \"/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin\"\n }\n\n // findPath returns a string containing the 'PATH' environment variable\n private static func findPath(_ env: [String]) -> String? {\n env.first(where: { path in\n let split = path.split(separator: \"=\")\n return split.count == 2 && split[0] == \"PATH\"\n })\n }\n\n // findExec returns true if the provided path is an executable\n private static func findExec(_ path: String) -> Bool {\n let fm = FileManager.default\n return fm.isExecutableFile(atPath: path)\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/UInt8+DataBinding.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension ArraySlice {\n package func hexEncodedString() -> String {\n self.map { String(format: \"%02hhx\", $0) }.joined()\n }\n}\n\nextension [UInt8] {\n package func hexEncodedString() -> String {\n self.map { String(format: \"%02hhx\", $0) }.joined()\n }\n\n package mutating func bind(as type: T.Type, offset: Int = 0, size: Int? = nil) -> UnsafeMutablePointer? {\n guard self.count >= (size ?? MemoryLayout.size) + offset else {\n return nil\n }\n\n return self.withUnsafeMutableBytes { $0.baseAddress?.advanced(by: offset).assumingMemoryBound(to: T.self) }\n }\n\n package mutating func copyIn(as type: T.Type, value: T, offset: Int = 0, size: Int? = nil) -> Int? {\n let size = size ?? MemoryLayout.size\n guard self.count >= size - offset else {\n return nil\n }\n\n return self.withUnsafeMutableBytes {\n $0.baseAddress?.advanced(by: offset).assumingMemoryBound(to: T.self).pointee = value\n return offset + MemoryLayout.size\n }\n }\n\n package mutating func copyOut(as type: T.Type, offset: Int = 0, size: Int? = nil) -> (Int, T)? {\n guard self.count >= (size ?? MemoryLayout.size) - offset else {\n return nil\n }\n\n return self.withUnsafeMutableBytes {\n guard let value = $0.baseAddress?.advanced(by: offset).assumingMemoryBound(to: T.self).pointee else {\n return nil\n }\n return (offset + MemoryLayout.size, value)\n }\n }\n\n package mutating func copyIn(buffer: [UInt8], offset: Int = 0) -> Int? {\n guard offset + buffer.count <= self.count else {\n return nil\n }\n\n self[offset.. Int? {\n guard offset + buffer.count <= self.count else {\n return nil\n }\n\n buffer[0.. [Int32: Int32] {\n var reaped = [Int32: Int32]()\n while true {\n guard let exit = wait() else {\n return reaped\n }\n reaped[exit.pid] = exit.status\n }\n return reaped\n }\n\n /// Returns the exit status of the last process that exited.\n /// nil is returned when no pending processes exist.\n private static func wait() -> Exit? {\n var rus = rusage()\n var ws = Int32()\n\n let pid = wait4(-1, &ws, WNOHANG, &rus)\n if pid <= 0 {\n return nil\n }\n return (pid: pid, status: Command.toExitStatus(ws))\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\n\n/**\n ```\n# EXT4 Filesystem Layout\n\n The EXT4 filesystem divides the disk into an upfront metadata section followed by several logical groups known as block groups. The\n metadata section looks like this:\n\n +--------------------------+\n | Boot Sector (1024) |\n +--------------------------+\n | Superblock (1024) |\n +--------------------------+\n | Empty (2048) |\n +--------------------------+\n | |\n | [Block Group Descriptors]|\n | |\n | - Free/used block bitmap |\n | - Free/used inode bitmap |\n | - Inode table pointer |\n | - Other metadata |\n | |\n +--------------------------+\n\n ## Block Groups\n\n Each block group optionally stores a copy of the superblock and group descriptor table for disaster recovery.\n The rest of the block group comprises of data blocks. The size of each block group is dynamically decided\n while formatting, based on total amount of space available on the disk.\n\n +--------------------------+\n | Block Group 0 |\n | +------------------+ |\n | | Super Block | |\n | +------------------+ |\n | | Group Desc. | |\n | +------------------+ |\n | | Data Blocks | |\n | | | |\n | +------------------+ |\n +--------------------------+\n | Block Group 1 |\n | +------------------+ |\n | | Super Block | |\n | +------------------+ |\n | | Group Desc. | |\n | +------------------+ |\n | | Data Blocks | |\n | | | |\n | +------------------+ |\n +--------------------------+\n | ... |\n +--------------------------+\n | Block Group N |\n | +------------------+ |\n | | Super Block | |\n | +------------------+ |\n | | Group Desc. | |\n | +------------------+ |\n | | Data Blocks | |\n | | | |\n | +------------------+ |\n +--------------------------+\n\n The descriptor for each block group contain the following information:\n\n - Block Bitmap\n - Inode Bitmap\n - Pointer to Inode Table\n - other metadata such as used block count, num. dirs etc.\n\n ### Block Bitmap\n\n A sequence of bits, where each bit represents a block in the block group.\n\n 1: In use block\n 0: Free block\n\n +---------------+---------------+\n | Block |\n | Bitmap |\n +---------------+---------------+\n | 1 0 1 0 1 1 0 0 |\n +---------------+---------------+\n | | | | | | | |\n | | | | | | | |\n v v v v v v v v\n +---+---+---+---+---+---+---+---+\n | B | | B | | B | B | | |\n +---+---+---+---+---+---+---+---+\n\n Whenever a file is created, free data blocks are identified by using this table.\n When it is deleted, the corresponding data blocks are marked as free.\n\n ### Inode Bitmap\n\n A sequence of bits, where each bit represents a inode in the block group. Since\n inodes per group is a fixed number, this bitmap is made to be of sufficient length\n to accommodate that many inodes\n\n 1: In use inode\n 0: Free inode\n\n +---------------+---------------+\n | Inode |\n | Bitmap |\n +---------------+---------------+\n | 1 0 1 0 1 1 0 0 |\n +---------------+---------------+\n | | | | | | | |\n | | | | | | | |\n v v v v v v v v\n +---+---+---+---+---+---+---+---+\n | I | | I | | I | I | | |\n +---+---+---+---+---+---+---+---+\n\n ## Inode table\n\n Inode table provides a mapping from Inode -> Data blocks. In this implementation, inode size is set to 256 bytes.\n Inode table uses extents to efficiently describe the mapping.\n\n +-----------------------+\n | Inode Table |\n +-----------------------+\n | Inode | Metadata |\n +-------+---------------+\n | 1 | permissions |\n | | size |\n | | user ID |\n | | group ID |\n | | timestamps |\n | | block |\n | | blocks count |\n +-------+---------------+\n | 2 | ... |\n +-------+---------------+\n | ... | ... |\n +-------+---------------+\n\n The length of `block` field in the inode table is 60 bytes. This field contains an extent tree\n that holds information about ranges of blocks used by the file. For smaller files, the entire extent\n tree can be stored within this field.\n\n +-----------------------+\n | Inode |\n +-----------------------+\n | Metadata |\n +-----------------------+\n | Extent Tree |\n | +-------------------+ |\n | | Extent Leaf Node | |\n | +-------------------+ |\n | | - Start Block | |\n | | - Block Count | |\n | | - ... | |\n | +-------------------+ |\n +-----------------------+\n\n For larger files which span across multiple non-contiguous blocks, extent tree's root points to extent\n blocks, which in-turn point to the blocks used by the file\n\n +-----------------------+\n | Extent Tree |\n | +-------------------+ |\n | | Extent Root | |\n | +-------------------+ |\n | | - Pointers to | |\n | | Extent Blocks | |\n | +-------------------+ |\n +-----------------------+\n |\n v\n +-----------------------+\n | Extent Block |\n +-----------------------+\n | +-------------------+ |\n | | Extent Leaf Node | |\n | +-------------------+ |\n | | - Start Block | |\n | | - Block Count | |\n | | - ... | |\n | +-------------------+ |\n | +-------------------+ |\n | | Extent Leaf Node | |\n | +-------------------+ |\n | | - Start Block | |\n | | - Block Count | |\n | | - ... | |\n | +-------------------+ |\n +-----------------------+\n\n ## Directory entries\n\n The data blocks for directory inodes point to a list of directory entrees. Each entry\n consists of only a name and inode number. The name and inode number correspond to the\n name and inode number of the children of the directory\n\n +-------------------------+\n | Directory Entry |\n +-------------------------+\n | inode | rec_len | name |\n +-------------------------+\n | 2 | 1 | \".\" |\n +-------------------------+\n | Directory Entry |\n +-------------------------+\n | inode | rec_len | name |\n +-------------------------+\n | 1 | 2 | \"..\" |\n +-------------------------+\n | Directory Entry |\n +-------------------------+\n | inode | rec_len | name |\n +-------------------------+\n | 11 | 10 | lost& |\n | | | found |\n +-------------------------+\n\nMore details can be found here https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout\n\n```\n*/\n\n/// A type for interacting with ext4 file systems.\n///\n/// The `Ext4` class provides functionality to read the superblock of an existing ext4 block device\n/// and format a new block device with the ext4 file system.\n///\n/// Usage:\n/// - To read the superblock of an existing ext4 block device, create an instance of `Ext4` with the\n/// path to the block device\n/// - To format a new block device with ext4, create an instance of `Ext4.Formatter` with the path to the block\n/// device and call the `close()` method.\n///\n/// Example 1: Read an existing block device\n/// ```swift\n/// let blockDevice = URL(filePath: \"/dev/sdb\")\n/// // succeeds if a valid ext4 fs is found at path\n/// let ext4 = try Ext4(blockDevice: blockDevice)\n/// print(\"Block size: \\(ext4.blockSize)\")\n/// print(\"Total size: \\(ext4.size)\")\n///\n/// // Reading the superblock\n/// let superblock = ext4.superblock\n/// print(\"Superblock information:\")\n/// print(\"Total blocks: \\(superblock.blocksCountLow)\")\n/// ```\n///\n/// Example 2: Format a new block device (Refer [`EXT4.Formatter`](x-source-tag://EXT4.Formatter) for more info)\n/// ```swift\n/// let devicePath = URL(filePath: \"/dev/sdc\")\n/// let formatter = try EXT4.Formatter(devicePath, blockSize: 4096)\n/// try formatter.close()\n/// ```\npublic enum EXT4 {\n public static let SuperBlockMagic: UInt16 = 0xef53\n\n static let ExtentHeaderMagic: UInt16 = 0xf30a\n static let XAttrHeaderMagic: UInt32 = 0xea02_0000\n\n static let DefectiveBlockInode: InodeNumber = 1\n static let RootInode: InodeNumber = 2\n static let FirstInode: InodeNumber = 11\n static let LostAndFoundInode: InodeNumber = 11\n\n static let InodeActualSize: UInt32 = 160 // 160 bytes used by metadata\n static let InodeExtraSize: UInt32 = 96 // 96 bytes for inline xattrs\n static let InodeSize: UInt32 = UInt32(MemoryLayout.size) // 256 bytes. This is the max size of an inode\n static let XattrInodeHeaderSize: UInt32 = 4\n static let XattrBlockHeaderSize: UInt32 = 32\n static let ExtraIsize: UInt16 = UInt16(InodeActualSize) - 128\n\n static let MaxLinks: UInt32 = 65000\n static let MaxBlocksPerExtent: UInt32 = 0x8000\n static let MaxFileSize: UInt64 = 128.gib()\n static let SuperBlockOffset: UInt64 = 1024\n}\n\nextension EXT4 {\n // `EXT4` errors.\n public enum Error: Swift.Error, CustomStringConvertible, Sendable, Equatable {\n case notFound(_ path: String)\n case couldNotReadSuperBlock(_ path: String, _ offset: UInt64, _ size: Int)\n case invalidSuperBlock\n case deepExtentsUnimplemented\n case invalidExtents\n case invalidXattrEntry\n case couldNotReadBlock(_ block: UInt32)\n case invalidPathEncoding(_ path: String)\n case couldNotReadInode(_ inode: UInt32)\n case couldNotReadGroup(_ group: UInt32)\n public var description: String {\n switch self {\n case .notFound(let path):\n return \"file at path \\(path) not found\"\n case .couldNotReadSuperBlock(let path, let offset, let size):\n return \"could not read \\(size) bytes of superblock from \\(path) at offset \\(offset)\"\n case .invalidSuperBlock:\n return \"not a valid EXT4 superblock\"\n case .deepExtentsUnimplemented:\n return \"deep extents are not supported\"\n case .invalidExtents:\n return \"extents invalid or corrupted\"\n case .invalidXattrEntry:\n return \"invalid extended attribute entry\"\n case .couldNotReadBlock(let block):\n return \"could not read block \\(block)\"\n case .invalidPathEncoding(let path):\n return \"path encoding for '\\(path)' is invalid, must be ascii or utf8\"\n case .couldNotReadInode(let inode):\n return \"could not read inode \\(inode)\"\n case .couldNotReadGroup(let group):\n return \"could not read group descriptor \\(group)\"\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Signals.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Helper type with utilities to parse and manipulate unix signals.\npublic struct Signals {\n /// Returns the numeric values of all known signals.\n public static func allNumeric() -> [Int32] {\n Array(Signals.all.values)\n }\n\n /// Parses a string representation of a signal (SIGKILL) and returns\n // the 32 bit integer representation (9).\n public static func parseSignal(_ signal: String) throws -> Int32 {\n if let sig = Int32(signal) {\n if !Signals.all.values.contains(sig) {\n throw Error.invalidSignal(signal)\n }\n return sig\n }\n var signalUpper = signal.uppercased()\n signalUpper.trimPrefix(\"SIG\")\n guard let sig = Signals.all[signalUpper] else {\n throw Error.invalidSignal(signal)\n }\n return sig\n }\n\n /// Errors that can be encountered for converting signals.\n public enum Error: Swift.Error, CustomStringConvertible {\n case invalidSignal(String)\n\n public var description: String {\n switch self {\n case .invalidSignal(let sig):\n return \"invalid signal: \\(sig)\"\n }\n }\n }\n}\n\n#if os(macOS)\n\nextension Signals {\n /// `all` returns all signals for the current platform.\n public static let all: [String: Int32] = [\n \"ABRT\": SIGABRT,\n \"ALRM\": SIGALRM,\n \"BUS\": SIGBUS,\n \"CHLD\": SIGCHLD,\n \"CONT\": SIGCONT,\n \"EMT\": SIGEMT,\n \"FPE\": SIGFPE,\n \"HUP\": SIGHUP,\n \"ILL\": SIGILL,\n \"INFO\": SIGINFO,\n \"INT\": SIGINT,\n \"IO\": SIGIO,\n \"IOT\": SIGIOT,\n \"KILL\": SIGKILL,\n \"PIPE\": SIGPIPE,\n \"PROF\": SIGPROF,\n \"QUIT\": SIGQUIT,\n \"SEGV\": SIGSEGV,\n \"STOP\": SIGSTOP,\n \"SYS\": SIGSYS,\n \"TERM\": SIGTERM,\n \"TRAP\": SIGTRAP,\n \"TSTP\": SIGTSTP,\n \"TTIN\": SIGTTIN,\n \"TTOU\": SIGTTOU,\n \"URG\": SIGURG,\n \"USR1\": SIGUSR1,\n \"USR2\": SIGUSR2,\n \"VTALRM\": SIGVTALRM,\n \"WINCH\": SIGWINCH,\n \"XCPU\": SIGXCPU,\n \"XFSZ\": SIGXFSZ,\n ]\n}\n\n#endif\n\n#if os(Linux)\n\nextension Signals {\n /// `all` returns all signals for the current platform.\n ///\n /// For Linux this isn't actually exhaustive as it excludes\n /// rtmin/rtmax entries.\n public static let all: [String: Int32] = [\n \"ABRT\": SIGABRT,\n \"ALRM\": SIGALRM,\n \"BUS\": SIGBUS,\n \"CHLD\": SIGCHLD,\n \"CLD\": SIGCHLD,\n \"CONT\": SIGCONT,\n \"FPE\": SIGFPE,\n \"HUP\": SIGHUP,\n \"ILL\": SIGILL,\n \"INT\": SIGINT,\n \"IO\": SIGIO,\n \"IOT\": SIGIOT,\n \"KILL\": SIGKILL,\n \"PIPE\": SIGPIPE,\n \"POLL\": SIGPOLL,\n \"PROF\": SIGPROF,\n \"PWR\": SIGPWR,\n \"QUIT\": SIGQUIT,\n \"SEGV\": SIGSEGV,\n \"STKFLT\": SIGSTKFLT,\n \"STOP\": SIGSTOP,\n \"SYS\": SIGSYS,\n \"TERM\": SIGTERM,\n \"TRAP\": SIGTRAP,\n \"TSTP\": SIGTSTP,\n \"TTIN\": SIGTTIN,\n \"TTOU\": SIGTTOU,\n \"URG\": SIGURG,\n \"USR1\": SIGUSR1,\n \"USR2\": SIGUSR2,\n \"VTALRM\": SIGVTALRM,\n \"WINCH\": SIGWINCH,\n \"XCPU\": SIGXCPU,\n \"XFSZ\": SIGXFSZ,\n ]\n}\n\n#endif\n"], ["/containerization/Sources/ContainerizationNetlink/NetlinkSocket.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A protocol for interacting with a netlink socket.\npublic protocol NetlinkSocket {\n var pid: UInt32 { get }\n func send(buf: UnsafeRawPointer!, len: Int, flags: Int32) throws -> Int\n func recv(buf: UnsafeMutableRawPointer!, len: Int, flags: Int32) throws -> Int\n}\n\n/// A netlink socket provider.\npublic typealias NetlinkSocketProvider = () throws -> any NetlinkSocket\n\n/// Errors thrown when interacting with a netlink socket.\npublic enum NetlinkSocketError: Swift.Error, CustomStringConvertible, Equatable {\n case socketFailure(rc: Int32)\n case bindFailure(rc: Int32)\n case sendFailure(rc: Int32)\n case recvFailure(rc: Int32)\n case notImplemented\n\n /// The description of the errors.\n public var description: String {\n switch self {\n case .socketFailure(let rc):\n return \"could not create netlink socket, rc = \\(rc)\"\n case .bindFailure(let rc):\n return \"could not bind netlink socket, rc = \\(rc)\"\n case .sendFailure(let rc):\n return \"could not send netlink packet, rc = \\(rc)\"\n case .recvFailure(let rc):\n return \"could not receive netlink packet, rc = \\(rc)\"\n case .notImplemented:\n return \"socket function not implemented for platform\"\n }\n }\n}\n\n#if canImport(Musl)\nimport Musl\nlet osSocket = Musl.socket\nlet osBind = Musl.bind\nlet osSend = Musl.send\nlet osRecv = Musl.recv\n\n/// A default implementation of `NetlinkSocket`.\npublic class DefaultNetlinkSocket: NetlinkSocket {\n private let sockfd: Int32\n\n /// The process identifier of the process creating this socket.\n public let pid: UInt32\n\n /// Creates a new instance.\n public init() throws {\n pid = UInt32(getpid())\n sockfd = osSocket(Int32(AddressFamily.AF_NETLINK), SocketType.SOCK_RAW, NetlinkProtocol.NETLINK_ROUTE)\n guard sockfd >= 0 else {\n throw NetlinkSocketError.socketFailure(rc: errno)\n }\n\n let addr = SockaddrNetlink(family: AddressFamily.AF_NETLINK, pid: pid)\n var buffer = [UInt8](repeating: 0, count: SockaddrNetlink.size)\n _ = try addr.appendBuffer(&buffer, offset: 0)\n guard let ptr = buffer.bind(as: sockaddr.self, size: buffer.count) else {\n throw NetlinkSocketError.bindFailure(rc: 0)\n }\n guard osBind(sockfd, ptr, UInt32(buffer.count)) >= 0 else {\n throw NetlinkSocketError.bindFailure(rc: errno)\n }\n }\n\n deinit {\n close(sockfd)\n }\n\n /// Sends a request to a netlink socket.\n /// Returns the number of bytes sent.\n /// - Parameters:\n /// - buf: The buffer to send.\n /// - len: The length of the buffer to send.\n /// - flags: The send flags.\n public func send(buf: UnsafeRawPointer!, len: Int, flags: Int32) throws -> Int {\n let count = osSend(sockfd, buf, len, flags)\n guard count >= 0 else {\n throw NetlinkSocketError.sendFailure(rc: errno)\n }\n\n return count\n }\n\n /// Receives a response from a netlink socket.\n /// Returns the number of bytes received.\n /// - Parameters:\n /// - buf: The buffer to receive into.\n /// - len: The maximum number of bytes to receive.\n /// - flags: The receive flags.\n public func recv(buf: UnsafeMutableRawPointer!, len: Int, flags: Int32) throws -> Int {\n let count = osRecv(sockfd, buf, len, flags)\n guard count >= 0 else {\n throw NetlinkSocketError.recvFailure(rc: errno)\n }\n\n return count\n }\n}\n#else\npublic class DefaultNetlinkSocket: NetlinkSocket {\n public var pid: UInt32 { 0 }\n\n public init() throws {}\n\n public func send(buf: UnsafeRawPointer!, len: Int, flags: Int32) throws -> Int {\n throw NetlinkSocketError.notImplemented\n }\n\n public func recv(buf: UnsafeMutableRawPointer!, len: Int, flags: Int32) throws -> Int {\n throw NetlinkSocketError.notImplemented\n }\n}\n#endif\n"], ["/containerization/Sources/ContainerizationOS/Keychain/KeychainQuery.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\n\n/// Holds the result of a query to the keychain.\npublic struct KeychainQueryResult {\n public var account: String\n public var data: String\n public var modifiedDate: Date\n public var createdDate: Date\n}\n\n/// Type that facilitates interacting with the macOS keychain.\npublic struct KeychainQuery {\n public init() {}\n\n /// Save a value to the keychain.\n public func save(id: String, host: String, user: String, token: String) throws {\n if try exists(id: id, host: host) {\n try delete(id: id, host: host)\n }\n\n guard let tokenEncoded = token.data(using: String.Encoding.utf8) else {\n throw Self.Error.invalidTokenConversion\n }\n let query: [String: Any] = [\n kSecClass as String: kSecClassInternetPassword,\n kSecAttrSecurityDomain as String: id,\n kSecAttrServer as String: host,\n kSecAttrAccount as String: user,\n kSecValueData as String: tokenEncoded,\n kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock,\n kSecAttrSynchronizable as String: false,\n ]\n let status = SecItemAdd(query as CFDictionary, nil)\n guard status == errSecSuccess else { throw Self.Error.unhandledError(status: status) }\n }\n\n /// Delete a value from the keychain.\n public func delete(id: String, host: String) throws {\n let query: [String: Any] = [\n kSecClass as String: kSecClassInternetPassword,\n kSecAttrSecurityDomain as String: id,\n kSecAttrServer as String: host,\n kSecMatchLimit as String: kSecMatchLimitOne,\n ]\n let status = SecItemDelete(query as CFDictionary)\n guard status == errSecSuccess || status == errSecItemNotFound else {\n throw Self.Error.unhandledError(status: status)\n }\n }\n\n /// Retrieve a value from the keychain.\n public func get(id: String, host: String) throws -> KeychainQueryResult? {\n let query: [String: Any] = [\n kSecClass as String: kSecClassInternetPassword,\n kSecAttrSecurityDomain as String: id,\n kSecAttrServer as String: host,\n kSecReturnAttributes as String: true,\n kSecMatchLimit as String: kSecMatchLimitOne,\n kSecReturnData as String: true,\n ]\n var item: CFTypeRef?\n let status = SecItemCopyMatching(query as CFDictionary, &item)\n let exists = try isQuerySuccessful(status)\n if !exists {\n return nil\n }\n\n guard let fetched = item as? [String: Any] else {\n throw Self.Error.unexpectedDataFetched\n }\n guard let data = fetched[kSecValueData as String] as? Data else {\n throw Self.Error.keyNotPresent(key: kSecValueData as String)\n }\n guard let decodedData = String(data: data, encoding: String.Encoding.utf8) else {\n throw Self.Error.unexpectedDataFetched\n }\n guard let account = fetched[kSecAttrAccount as String] as? String else {\n throw Self.Error.keyNotPresent(key: kSecAttrAccount as String)\n }\n guard let modifiedDate = fetched[kSecAttrModificationDate as String] as? Date else {\n throw Self.Error.keyNotPresent(key: kSecAttrModificationDate as String)\n }\n guard let createdDate = fetched[kSecAttrCreationDate as String] as? Date else {\n throw Self.Error.keyNotPresent(key: kSecAttrCreationDate as String)\n }\n return KeychainQueryResult(\n account: account,\n data: decodedData,\n modifiedDate: modifiedDate,\n createdDate: createdDate\n )\n }\n\n private func isQuerySuccessful(_ status: Int32) throws -> Bool {\n guard status != errSecItemNotFound else {\n return false\n }\n guard status == errSecSuccess else {\n throw Self.Error.unhandledError(status: status)\n }\n return true\n }\n\n /// Check if a value exists in the keychain.\n public func exists(id: String, host: String) throws -> Bool {\n let query: [String: Any] = [\n kSecClass as String: kSecClassInternetPassword,\n kSecAttrSecurityDomain as String: id,\n kSecAttrServer as String: host,\n kSecReturnAttributes as String: true,\n kSecMatchLimit as String: kSecMatchLimitOne,\n kSecReturnData as String: false,\n ]\n\n let status = SecItemCopyMatching(query as CFDictionary, nil)\n return try isQuerySuccessful(status)\n }\n}\n\nextension KeychainQuery {\n public enum Error: Swift.Error {\n case unhandledError(status: Int32)\n case unexpectedDataFetched\n case keyNotPresent(key: String)\n case invalidTokenConversion\n }\n}\n#endif\n"], ["/containerization/Sources/ContainerizationOS/Pipe+Close.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension Pipe {\n /// Close both sides of the pipe.\n public func close() throws {\n var err: Swift.Error?\n do {\n try self.fileHandleForReading.close()\n } catch {\n err = error\n }\n try self.fileHandleForWriting.close()\n if let err {\n throw err\n }\n }\n\n /// Ensure that both sides of the pipe are set with O_CLOEXEC.\n public func setCloexec() throws {\n if fcntl(self.fileHandleForWriting.fileDescriptor, F_SETFD, FD_CLOEXEC) == -1 {\n throw POSIXError(.init(rawValue: errno)!)\n }\n if fcntl(self.fileHandleForReading.fileDescriptor, F_SETFD, FD_CLOEXEC) == -1 {\n throw POSIXError(.init(rawValue: errno)!)\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/URL+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// The `resolvingSymlinksInPath` method of the `URL` struct does not resolve the symlinks\n/// for directories under `/private` which include`tmp`, `var` and `etc`\n/// hence adding a method to build up on the existing `resolvingSymlinksInPath` that prepends `/private` to those paths\nextension URL {\n /// returns the unescaped absolutePath of a URL joined by separator\n func absolutePath(_ separator: String = \"/\") -> String {\n self.pathComponents\n .joined(separator: separator)\n .dropFirst(\"/\".count)\n .description\n }\n\n public func resolvingSymlinksInPathWithPrivate() -> URL {\n let url = self.resolvingSymlinksInPath()\n #if os(macOS)\n let parts = url.pathComponents\n if parts.count > 1 {\n if (parts.first == \"/\") && [\"tmp\", \"var\", \"etc\"].contains(parts[1]) {\n if let resolved = NSURL.fileURL(withPathComponents: [\"/\", \"private\"] + parts[1...]) {\n return resolved\n }\n }\n }\n #endif\n return url\n }\n\n public var isDirectory: Bool {\n (try? resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true\n }\n\n public var isSymlink: Bool {\n (try? resourceValues(forKeys: [.isSymbolicLinkKey]))?.isSymbolicLink == true\n }\n}\n"], ["/containerization/Sources/Containerization/Kernel.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// An object representing a Linux kernel used to boot a virtual machine.\n/// In addition to a path to the kernel itself, this type stores relevant\n/// data such as the commandline to pass to the kernel, and init arguments.\npublic struct Kernel: Sendable, Codable {\n /// The command line arguments passed to the kernel on boot.\n public struct CommandLine: Sendable, Codable {\n public static let kernelDefaults = [\n \"console=hvc0\",\n \"tsc=reliable\",\n ]\n\n /// Adds the debug argument to the kernel commandline.\n mutating public func addDebug() {\n self.kernelArgs.append(\"debug\")\n }\n\n /// Adds a panic level to the kernel commandline.\n mutating public func addPanic(level: Int) {\n self.kernelArgs.append(\"panic=\\(level)\")\n }\n\n /// Additional kernel arguments.\n public var kernelArgs: [String]\n /// Additional arguments passed to the Initial Process / Agent.\n public var initArgs: [String]\n\n /// Initializes the kernel commandline using the mix of kernel arguments\n /// and init arguments.\n public init(\n kernelArgs: [String] = kernelDefaults,\n initArgs: [String] = []\n ) {\n self.kernelArgs = kernelArgs\n self.initArgs = initArgs\n }\n\n /// Initializes the kernel commandline to the defaults of Self.kernelDefaults,\n /// adds a debug and panic flag as instructed, and optionally a set of init\n /// process flags to supply to vminitd.\n public init(debug: Bool, panic: Int, initArgs: [String] = []) {\n var args = Self.kernelDefaults\n if debug {\n args.append(\"debug\")\n }\n args.append(\"panic=\\(panic)\")\n self.kernelArgs = args\n self.initArgs = initArgs\n }\n }\n\n /// Path on disk to the kernel binary.\n public var path: URL\n /// Platform for the kernel.\n public var platform: SystemPlatform\n /// Kernel and init process command line.\n public var commandLine: Self.CommandLine\n\n /// Kernel command line arguments.\n public var kernelArgs: [String] {\n self.commandLine.kernelArgs\n }\n\n /// Init process arguments.\n public var initArgs: [String] {\n self.commandLine.initArgs\n }\n\n public init(\n path: URL,\n platform: SystemPlatform,\n commandline: Self.CommandLine = CommandLine(debug: false, panic: 0)\n ) {\n self.path = path\n self.platform = platform\n self.commandLine = commandline\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/File.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Trivial type to discover information about a given file (uid, gid, mode...).\npublic struct File: Sendable {\n /// `File` errors.\n public enum Error: Swift.Error, CustomStringConvertible {\n case errno(_ e: Int32)\n\n public var description: String {\n switch self {\n case .errno(let code):\n return \"errno \\(code)\"\n }\n }\n }\n\n /// Returns a `FileInfo` struct with information about the file.\n /// - Parameters:\n /// - url: The path to the file.\n public static func info(_ url: URL) throws -> FileInfo {\n try info(url.path)\n }\n\n /// Returns a `FileInfo` struct with information about the file.\n /// - Parameters:\n /// - path: The path to the file as a string.\n public static func info(_ path: String) throws -> FileInfo {\n var st = stat()\n guard stat(path, &st) == 0 else {\n throw Error.errno(errno)\n }\n return FileInfo(path, stat: st)\n }\n}\n\n/// `FileInfo` holds and provides easy access to stat(2) data\n/// for a file.\npublic struct FileInfo: Sendable {\n private let _stat_t: Foundation.stat\n private let _path: String\n\n init(_ path: String, stat: stat) {\n self._path = path\n self._stat_t = stat\n }\n\n /// mode_t for the file.\n public var mode: mode_t {\n self._stat_t.st_mode\n }\n\n /// The files uid.\n public var uid: Int {\n Int(self._stat_t.st_uid)\n }\n\n /// The files gid.\n public var gid: Int {\n Int(self._stat_t.st_gid)\n }\n\n /// The filesystem ID the file belongs to.\n public var dev: Int {\n Int(self._stat_t.st_dev)\n }\n\n /// The files inode number.\n public var ino: Int {\n Int(self._stat_t.st_ino)\n }\n\n /// The size of the file.\n public var size: Int {\n Int(self._stat_t.st_size)\n }\n\n /// The path to the file.\n public var path: String {\n self._path\n }\n\n /// Returns if the file is a directory.\n public var isDirectory: Bool {\n mode & S_IFMT == S_IFDIR\n }\n\n /// Returns if the file is a pipe.\n public var isPipe: Bool {\n mode & S_IFMT == S_IFIFO\n }\n\n /// Returns if the file is a socket.\n public var isSocket: Bool {\n mode & S_IFMT == S_IFSOCK\n }\n\n /// Returns if the file is a link.\n public var isLink: Bool {\n mode & S_IFMT == S_IFLNK\n }\n\n /// Returns if the file is a regular file.\n public var isRegularFile: Bool {\n mode & S_IFMT == S_IFREG\n }\n\n /// Returns if the file is a block device.\n public var isBlock: Bool {\n mode & S_IFMT == S_IFBLK\n }\n\n /// Returns if the file is a character device.\n public var isChar: Bool {\n mode & S_IFMT == S_IFCHR\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/ArchiveError.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CArchive\nimport Foundation\n\n/// An enumeration of the errors that can be thrown while interacting with an archive.\npublic enum ArchiveError: Error, CustomStringConvertible {\n case unableToCreateArchive\n case noUnderlyingArchive\n case noArchiveInCallback\n case noDelegateConfigured\n case delegateFreedBeforeCallback\n case unableToSetFormat(CInt, Format)\n case unableToAddFilter(CInt, Filter)\n case unableToWriteEntryHeader(CInt)\n case unableToWriteData(CLong)\n case unableToCloseArchive(CInt)\n case unableToOpenArchive(CInt)\n case unableToSetOption(CInt)\n case failedToSetLocale(locales: [String])\n case failedToGetProperty(String, URLResourceKey)\n case failedToDetectFilter\n case failedToDetectFormat\n case failedToExtractArchive(String)\n\n /// Description of the error\n public var description: String {\n switch self {\n case .unableToCreateArchive:\n return \"Unable to create an archive.\"\n case .noUnderlyingArchive:\n return \"No underlying archive was provided.\"\n case .noArchiveInCallback:\n return \"No archive was provided in the callback.\"\n case .noDelegateConfigured:\n return \"No delegate was configured.\"\n case .delegateFreedBeforeCallback:\n return \"The delegate was freed before the callback was invoked.\"\n case .unableToSetFormat(let code, let name):\n return \"Unable to set the archive format \\(name), code \\(code)\"\n case .unableToAddFilter(let code, let name):\n return \"Unable to set the archive filter \\(name), code \\(code)\"\n case .unableToWriteEntryHeader(let code):\n return \"Unable to write the entry header to the archive. Error code \\(code)\"\n case .unableToWriteData(let code):\n return \"Unable to write data to the archive. Error code \\(code)\"\n case .unableToCloseArchive(let code):\n return \"Unable to close the archive. Error code \\(code)\"\n case .unableToOpenArchive(let code):\n return \"Unable to open the archive. Error code \\(code)\"\n case .unableToSetOption(_):\n return \"Unable to set an option on the archive.\"\n case .failedToSetLocale(let locales):\n return \"Failed to set locale to \\(locales)\"\n case .failedToGetProperty(let path, let propertyName):\n return \"Failed to read property \\(propertyName) from file at path \\(path)\"\n case .failedToDetectFilter:\n return \"Failed to detect filter from archive.\"\n case .failedToDetectFormat:\n return \"Failed to detect format from archive.\"\n case .failedToExtractArchive(let reason):\n return \"Failed to extract archive: \\(reason)\"\n }\n }\n}\n\npublic struct LibArchiveError: Error {\n public let source: ArchiveError\n public let description: String\n}\n\nfunc wrap(_ f: @autoclosure () -> CInt, _ e: (CInt) -> ArchiveError, underlying: OpaquePointer? = nil) throws {\n let result = f()\n guard result == ARCHIVE_OK else {\n let error = e(result)\n guard let underlying = underlying,\n let description = archive_error_string(underlying).map(String.init(cString:))\n else {\n throw error\n }\n throw LibArchiveError(source: error, description: description)\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/ContentWriter.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Crypto\nimport Foundation\nimport NIOCore\n\n/// Provides a context to write data into a directory.\npublic class ContentWriter {\n private let base: URL\n private let encoder = JSONEncoder()\n\n /// Create a new ContentWriter.\n /// - Parameters:\n /// - base: The URL to write content to. If this is not a directory a\n /// ContainerizationError will be thrown with a code of .internalError.\n public init(for base: URL) throws {\n self.encoder.outputFormatting = [JSONEncoder.OutputFormatting.sortedKeys]\n\n self.base = base\n var isDirectory = ObjCBool(true)\n let exists = FileManager.default.fileExists(atPath: base.path, isDirectory: &isDirectory)\n\n guard exists && isDirectory.boolValue else {\n throw ContainerizationError(.internalError, message: \"Cannot create ContentWriter for path \\(base.absolutePath()). Not a directory\")\n }\n }\n\n /// Writes the data blob to the base URL provided in the constructor.\n /// - Parameters:\n /// - data: The data blob to write to a file under the base path.\n @discardableResult\n public func write(_ data: Data) throws -> (size: Int64, digest: SHA256.Digest) {\n let digest = SHA256.hash(data: data)\n let destination = base.appendingPathComponent(digest.encoded)\n try data.write(to: destination)\n return (Int64(data.count), digest)\n }\n\n /// Reads the data present in the passed in URL and writes it to the base path.\n /// - Parameters:\n /// - url: The URL to read the data from.\n @discardableResult\n public func create(from url: URL) throws -> (size: Int64, digest: SHA256.Digest) {\n let data = try Data(contentsOf: url)\n return try self.write(data)\n }\n\n /// Encodes the passed in type as a JSON blob and writes it to the base path.\n /// - Parameters:\n /// - content: The type to convert to JSON.\n @discardableResult\n public func create(from content: T) throws -> (size: Int64, digest: SHA256.Digest) {\n let data = try self.encoder.encode(content)\n return try self.write(data)\n }\n}\n"], ["/containerization/Sources/SendablePropertyMacros/SendablePropertyMacro.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SwiftCompilerPlugin\nimport SwiftParser\nimport SwiftSyntax\nimport SwiftSyntaxBuilder\nimport SwiftSyntaxMacros\n\n/// A macro that allows to make a property of a supported type thread-safe keeping the `Sendable` conformance of the type.\npublic struct SendablePropertyMacro: PeerMacro {\n private static let allowedTypes: Set = [\n \"Int\", \"UInt\", \"Int16\", \"UInt16\", \"Int32\", \"UInt32\", \"Int64\", \"UInt64\", \"Float\", \"Double\", \"Bool\", \"UnsafeRawPointer\", \"UnsafeMutableRawPointer\", \"UnsafePointer\",\n \"UnsafeMutablePointer\",\n ]\n\n private static func checkPropertyType(in declaration: some DeclSyntaxProtocol) throws {\n guard let varDecl = declaration.as(VariableDeclSyntax.self),\n let binding = varDecl.bindings.first,\n let typeAnnotation = binding.typeAnnotation,\n let id = typeAnnotation.type.as(IdentifierTypeSyntax.self)\n else {\n // Nothing to check.\n return\n }\n\n var typeName = id.name.text\n // Allow optionals of the allowed types.\n if typeName.prefix(9) == \"Optional<\" && typeName.suffix(1) == \">\" {\n typeName = String(typeName.dropFirst(9).dropLast(1))\n }\n // Allow generics of the allowed types.\n if typeName.contains(\"<\") {\n typeName = String(typeName.prefix { $0 != \"<\" })\n }\n\n guard allowedTypes.contains(typeName) else {\n throw SendablePropertyError.notApplicableToType\n }\n }\n\n /// The macro expansion that introduces a `Sendable`-conforming \"peer\" declaration for a thread-safe storage for the value of the given declaration of a variable.\n /// - Parameters:\n /// - node: The given attribute node.\n /// - declaration: The given declaration.\n /// - context: The macro expansion context.\n public static func expansion(\n of node: SwiftSyntax.AttributeSyntax, providingPeersOf declaration: some SwiftSyntax.DeclSyntaxProtocol, in context: some SwiftSyntaxMacros.MacroExpansionContext\n ) throws -> [SwiftSyntax.DeclSyntax] {\n try checkPropertyType(in: declaration)\n return try SendablePropertyMacroUnchecked.expansion(of: node, providingPeersOf: declaration, in: context)\n }\n}\n\nextension SendablePropertyMacro: AccessorMacro {\n /// The macro expansion that adds `Sendable`-conforming accessors to the given declaration of a variable.\n /// - Parameters:\n /// - node: The given attribute node.\n /// - declaration: The given declaration.\n /// - context: The macro expansion context.\n public static func expansion(\n of node: SwiftSyntax.AttributeSyntax, providingAccessorsOf declaration: some SwiftSyntax.DeclSyntaxProtocol, in context: some SwiftSyntaxMacros.MacroExpansionContext\n ) throws -> [SwiftSyntax.AccessorDeclSyntax] {\n try checkPropertyType(in: declaration)\n return try SendablePropertyMacroUnchecked.expansion(of: node, providingAccessorsOf: declaration, in: context)\n }\n}\n"], ["/containerization/Sources/ContainerizationNetlink/Types.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport Foundation\n\nstruct SocketType {\n static let SOCK_RAW: Int32 = 3\n}\n\nstruct AddressFamily {\n static let AF_UNSPEC: UInt16 = 0\n static let AF_INET: UInt16 = 2\n static let AF_INET6: UInt16 = 10\n static let AF_NETLINK: UInt16 = 16\n static let AF_PACKET: UInt16 = 17\n}\n\nstruct NetlinkProtocol {\n static let NETLINK_ROUTE: Int32 = 0\n}\n\nstruct NetlinkType {\n static let NLMSG_NOOP: UInt16 = 1\n static let NLMSG_ERROR: UInt16 = 2\n static let NLMSG_DONE: UInt16 = 3\n static let NLMSG_OVERRUN: UInt16 = 4\n static let RTM_NEWLINK: UInt16 = 16\n static let RTM_DELLINK: UInt16 = 17\n static let RTM_GETLINK: UInt16 = 18\n static let RTM_NEWADDR: UInt16 = 20\n static let RTM_NEWROUTE: UInt16 = 24\n}\n\nstruct NetlinkFlags {\n static let NLM_F_REQUEST: UInt16 = 0x01\n static let NLM_F_MULTI: UInt16 = 0x02\n static let NLM_F_ACK: UInt16 = 0x04\n static let NLM_F_ECHO: UInt16 = 0x08\n static let NLM_F_DUMP_INTR: UInt16 = 0x10\n static let NLM_F_DUMP_FILTERED: UInt16 = 0x20\n\n // GET request\n static let NLM_F_ROOT: UInt16 = 0x100\n static let NLM_F_MATCH: UInt16 = 0x200\n static let NLM_F_ATOMIC: UInt16 = 0x400\n static let NLM_F_DUMP: UInt16 = NetlinkFlags.NLM_F_ROOT | NetlinkFlags.NLM_F_MATCH\n\n // NEW request flags\n static let NLM_F_REPLACE: UInt16 = 0x100\n static let NLM_F_EXCL: UInt16 = 0x200\n static let NLM_F_CREATE: UInt16 = 0x400\n static let NLM_F_APPEND: UInt16 = 0x800\n}\n\nstruct NetlinkScope {\n static let RT_SCOPE_UNIVERSE: UInt8 = 0\n}\n\nstruct InterfaceFlags {\n static let IFF_UP: UInt32 = 1 << 0\n static let DEFAULT_CHANGE: UInt32 = 0xffff_ffff\n}\n\nstruct LinkAttributeType {\n static let IFLA_EXT_IFNAME: UInt16 = 3\n static let IFLA_MTU: UInt16 = 4\n static let IFLA_EXT_MASK: UInt16 = 29\n}\n\nstruct LinkAttributeMaskFilter {\n static let RTEXT_FILTER_VF: UInt32 = 1 << 0\n static let RTEXT_FILTER_SKIP_STATS: UInt32 = 1 << 3\n}\n\nstruct AddressAttributeType {\n // subnet mask\n static let IFA_ADDRESS: UInt16 = 1\n // IPv4 address\n static let IFA_LOCAL: UInt16 = 2\n}\n\nstruct RouteTable {\n static let MAIN: UInt8 = 254\n}\n\nstruct RouteProtocol {\n static let UNSPEC: UInt8 = 0\n static let REDIRECT: UInt8 = 1\n static let KERNEL: UInt8 = 2\n static let BOOT: UInt8 = 3\n static let STATIC: UInt8 = 4\n}\n\nstruct RouteScope {\n static let UNIVERSE: UInt8 = 0\n static let LINK: UInt8 = 253\n}\n\nstruct RouteType {\n static let UNSPEC: UInt8 = 0\n static let UNICAST: UInt8 = 1\n}\n\nstruct RouteAttributeType {\n static let UNSPEC: UInt16 = 0\n static let DST: UInt16 = 1\n static let SRC: UInt16 = 2\n static let IIF: UInt16 = 3\n static let OIF: UInt16 = 4\n static let GATEWAY: UInt16 = 5\n static let PRIORITY: UInt16 = 6\n static let PREFSRC: UInt16 = 7\n}\n\nprotocol Bindable: Equatable {\n static var size: Int { get }\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int\n}\n\nstruct SockaddrNetlink: Bindable {\n static let size = 12\n\n var family: UInt16\n var pad: UInt16 = 0\n var pid: UInt32\n var groups: UInt32\n\n init(family: UInt16 = 0, pid: UInt32 = 0, groups: UInt32 = 0) {\n self.family = family\n self.pid = pid\n self.groups = groups\n }\n\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let offset = buffer.copyIn(as: UInt16.self, value: family, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: pid, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: groups, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n family = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n pid = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n groups = value\n\n return offset + Self.size\n }\n}\n\nstruct NetlinkMessageHeader: Bindable {\n static let size = 16\n\n var len: UInt32\n var type: UInt16\n var flags: UInt16\n var seq: UInt32\n var pid: UInt32\n\n init(len: UInt32 = 0, type: UInt16 = 0, flags: UInt16 = 0, seq: UInt32? = nil, pid: UInt32 = 0) {\n self.len = len\n self.type = type\n self.flags = flags\n self.seq = seq ?? UInt32.random(in: 0.. Int {\n guard let offset = buffer.copyIn(as: UInt32.self, value: len, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt16.self, value: type, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt16.self, value: flags, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: seq, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: pid, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n len = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n type = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n flags = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n seq = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n pid = value\n\n return offset\n }\n\n var moreResponses: Bool {\n (self.flags & NetlinkFlags.NLM_F_MULTI) != 0\n && (self.type != NetlinkType.NLMSG_DONE && self.type != NetlinkType.NLMSG_ERROR\n && self.type != NetlinkType.NLMSG_OVERRUN)\n }\n}\n\nstruct InterfaceInfo: Bindable {\n static let size = 16\n\n var family: UInt8\n var _pad: UInt8 = 0\n var type: UInt16\n var index: Int32\n var flags: UInt32\n var change: UInt32\n\n init(\n family: UInt8 = UInt8(AddressFamily.AF_UNSPEC), type: UInt16 = 0, index: Int32 = 0, flags: UInt32 = 0,\n change: UInt32 = 0\n ) {\n self.family = family\n self.type = type\n self.index = index\n self.flags = flags\n self.change = change\n }\n\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let offset = buffer.copyIn(as: UInt8.self, value: family, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: _pad, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt16.self, value: type, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: Int32.self, value: index, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: flags, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: change, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n family = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n _pad = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n type = value\n\n guard let (offset, value) = buffer.copyOut(as: Int32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n index = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n flags = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n change = value\n\n return offset\n }\n}\n\nstruct AddressInfo: Bindable {\n static let size = 8\n\n var family: UInt8\n var prefixLength: UInt8\n var flags: UInt8\n var scope: UInt8\n var index: UInt32\n\n init(\n family: UInt8 = UInt8(AddressFamily.AF_UNSPEC), prefixLength: UInt8 = 32, flags: UInt8 = 0, scope: UInt8 = 0,\n index: UInt32 = 0\n ) {\n self.family = family\n self.prefixLength = prefixLength\n self.flags = flags\n self.scope = scope\n self.index = index\n }\n\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let offset = buffer.copyIn(as: UInt8.self, value: family, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: prefixLength, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: flags, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: scope, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: index, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n family = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n prefixLength = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n flags = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n scope = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n index = value\n\n return offset\n }\n}\n\nstruct RouteInfo: Bindable {\n static let size = 12\n\n var family: UInt8\n var dstLen: UInt8\n var srcLen: UInt8\n var tos: UInt8\n var table: UInt8\n var proto: UInt8\n var scope: UInt8\n var type: UInt8\n var flags: UInt32\n\n init(\n family: UInt8 = UInt8(AddressFamily.AF_INET),\n dstLen: UInt8,\n srcLen: UInt8,\n tos: UInt8,\n table: UInt8,\n proto: UInt8,\n scope: UInt8,\n type: UInt8,\n flags: UInt32\n ) {\n self.family = family\n self.dstLen = dstLen\n self.srcLen = srcLen\n self.tos = tos\n self.table = table\n self.proto = proto\n self.scope = scope\n self.type = type\n self.flags = flags\n }\n\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let offset = buffer.copyIn(as: UInt8.self, value: family, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: dstLen, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: srcLen, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: tos, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: table, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: proto, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: scope, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: type, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: flags, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n family = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n dstLen = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n srcLen = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n tos = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n table = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n proto = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n scope = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n type = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n flags = value\n\n return offset\n }\n}\n\n/// A route information.\npublic struct RTAttribute: Bindable {\n static let size = 4\n\n public var len: UInt16\n public var type: UInt16\n public var paddedLen: Int { Int(((len + 3) >> 2) << 2) }\n\n init(len: UInt16 = 0, type: UInt16 = 0) {\n self.len = len\n self.type = type\n }\n\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let offset = buffer.copyIn(as: UInt16.self, value: len, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt16.self, value: type, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n len = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n type = value\n\n return offset\n }\n}\n\n/// A route information with data.\npublic struct RTAttributeData {\n public let attribute: RTAttribute\n public let data: [UInt8]\n}\n\n/// A response from the get link command.\npublic struct LinkResponse {\n public let interfaceIndex: Int32\n public let attrDatas: [RTAttributeData]\n}\n\n/// Errors thrown when parsing netlink data.\npublic enum NetlinkDataError: Swift.Error, CustomStringConvertible, Equatable {\n case sendMarshalFailure\n case recvUnmarshalFailure\n case responseError(rc: Int32)\n case unsupportedPlatform\n\n /// The description of the errors.\n public var description: String {\n switch self {\n case .sendMarshalFailure:\n return \"could not marshal netlink packet\"\n case .recvUnmarshalFailure:\n return \"could not unmarshal netlink packet\"\n case .responseError(let rc):\n return \"netlink response indicates error, rc = \\(rc)\"\n case .unsupportedPlatform:\n return \"unsupported platform\"\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/ImageConfig.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// Source: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/config.go\n\nimport Foundation\n\n/// ImageConfig defines the execution parameters which should be used as a base when running a container using an image.\npublic struct ImageConfig: Codable, Sendable {\n enum CodingKeys: String, CodingKey {\n case user = \"User\"\n case env = \"Env\"\n case entrypoint = \"Entrypoint\"\n case cmd = \"Cmd\"\n case workingDir = \"WorkingDir\"\n case labels = \"Labels\"\n case stopSignal = \"StopSignal\"\n }\n\n /// user defines the username or UID which the process in the container should run as.\n public let user: String?\n\n /// env is a list of environment variables to be used in a container.\n public let env: [String]?\n\n /// entrypoint defines a list of arguments to use as the command to execute when the container starts.\n public let entrypoint: [String]?\n\n /// cmd defines the default arguments to the entrypoint of the container.\n public let cmd: [String]?\n\n /// workingDir sets the current working directory of the entrypoint process in the container.\n public let workingDir: String?\n\n /// labels contains arbitrary metadata for the container.\n public let labels: [String: String]?\n\n /// stopSignal contains the system call signal that will be sent to the container to exit.\n public let stopSignal: String?\n\n public init(\n user: String? = nil, env: [String]? = nil, entrypoint: [String]? = nil, cmd: [String]? = nil,\n workingDir: String? = nil, labels: [String: String]? = nil, stopSignal: String? = nil\n ) {\n self.user = user\n self.env = env\n self.entrypoint = entrypoint\n self.cmd = cmd\n self.workingDir = workingDir\n self.labels = labels\n self.stopSignal = stopSignal\n }\n}\n\n/// RootFS describes a layer content addresses\npublic struct Rootfs: Codable, Sendable {\n enum CodingKeys: String, CodingKey {\n case type\n case diffIDs = \"diff_ids\"\n }\n\n /// type is the type of the rootfs.\n public let type: String\n\n /// diffIDs is an array of layer content hashes (DiffIDs), in order from bottom-most to top-most.\n public let diffIDs: [String]\n\n public init(type: String, diffIDs: [String]) {\n self.type = type\n self.diffIDs = diffIDs\n }\n}\n\n/// History describes the history of a layer.\npublic struct History: Codable, Sendable {\n enum CodingKeys: String, CodingKey {\n case created\n case createdBy = \"created_by\"\n case author\n case comment\n case emptyLayer = \"empty_layer\"\n }\n\n /// created is the combined date and time at which the layer was created, formatted as defined by RFC 3339, section 5.6.\n public let created: String?\n\n /// createdBy is the command which created the layer.\n public let createdBy: String?\n\n /// author is the author of the build point.\n public let author: String?\n\n /// comment is a custom message set when creating the layer.\n public let comment: String?\n\n /// emptyLayer is used to mark if the history item created a filesystem diff.\n public let emptyLayer: Bool?\n\n public init(\n created: String? = nil, createdBy: String? = nil, author: String? = nil, comment: String? = nil,\n emptyLayer: Bool? = nil\n ) {\n self.created = created\n self.createdBy = createdBy\n self.author = author\n self.comment = comment\n self.emptyLayer = emptyLayer\n }\n}\n\n/// Image is the JSON structure which describes some basic information about the image.\n/// This provides the `application/vnd.oci.image.config.v1+json` mediatype when marshalled to JSON.\npublic struct Image: Codable, Sendable {\n /// created is the combined date and time at which the image was created, formatted as defined by RFC 3339, section 5.6.\n public let created: String?\n\n /// author defines the name and/or email address of the person or entity which created and is responsible for maintaining the image.\n public let author: String?\n\n /// architecture field specifies the CPU architecture, for example `amd64` or `ppc64`.\n public let architecture: String\n\n /// os specifies the operating system, for example `linux` or `windows`.\n public let os: String\n\n /// osVersion is an optional field specifying the operating system version, for example on Windows `10.0.14393.1066`.\n public let osVersion: String?\n\n /// osFeatures is an optional field specifying an array of strings, each listing a required OS feature (for example on Windows `win32k`).\n public let osFeatures: [String]?\n\n /// variant is an optional field specifying a variant of the CPU, for example `v7` to specify ARMv7 when architecture is `arm`.\n public let variant: String?\n\n /// config defines the execution parameters which should be used as a base when running a container using the image.\n public let config: ImageConfig?\n\n /// rootfs references the layer content addresses used by the image.\n public let rootfs: Rootfs\n\n /// history describes the history of each layer.\n public let history: [History]?\n\n public init(\n created: String? = nil, author: String? = nil, architecture: String, os: String, osVersion: String? = nil,\n osFeatures: [String]? = nil, variant: String? = nil, config: ImageConfig? = nil, rootfs: Rootfs,\n history: [History]? = nil\n ) {\n self.created = created\n self.author = author\n self.architecture = architecture\n self.os = os\n self.osVersion = osVersion\n self.osFeatures = osFeatures\n self.variant = variant\n self.config = config\n self.rootfs = rootfs\n self.history = history\n }\n}\n"], ["/containerization/Sources/cctl/cctl.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationOCI\nimport Foundation\nimport Logging\n\nlet log = {\n LoggingSystem.bootstrap(StreamLogHandler.standardError)\n var log = Logger(label: \"com.apple.containerization\")\n log.logLevel = .debug\n return log\n}()\n\n@main\nstruct Application: AsyncParsableCommand {\n static let keychainID = \"com.apple.containerization\"\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.containerization\")\n }()\n\n private static let _contentStore: ContentStore = {\n try! LocalContentStore(path: appRoot.appendingPathComponent(\"content\"))\n }()\n\n private static let _imageStore: ImageStore = {\n try! ImageStore(\n path: appRoot,\n contentStore: contentStore\n )\n }()\n\n static var imageStore: ImageStore {\n _imageStore\n }\n\n static var contentStore: ContentStore {\n _contentStore\n }\n\n static let configuration = CommandConfiguration(\n commandName: \"cctl\",\n abstract: \"Utility CLI for Containerization\",\n version: \"2.0.0\",\n subcommands: [\n Images.self,\n Login.self,\n Rootfs.self,\n Run.self,\n ]\n )\n}\n\nextension String {\n var absoluteURL: URL {\n URL(fileURLWithPath: self).absoluteURL\n }\n}\n\nextension String: Swift.Error {\n\n}\n"], ["/containerization/Sources/ContainerizationOCI/State.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum ContainerState: String, Codable, Sendable {\n case creating\n case created\n case running\n case stopped\n}\n\npublic struct State: Codable, Sendable {\n public init(\n version: String,\n id: String,\n status: ContainerState,\n pid: Int,\n bundle: String,\n annotations: [String: String]?\n ) {\n self.ociVersion = version\n self.id = id\n self.status = status\n self.pid = pid\n self.bundle = bundle\n self.annotations = annotations\n }\n\n public init(instance: State) {\n self.ociVersion = instance.ociVersion\n self.id = instance.id\n self.status = instance.status\n self.pid = instance.pid\n self.bundle = instance.bundle\n self.annotations = instance.annotations\n }\n\n public let ociVersion: String\n public let id: String\n public let status: ContainerState\n public let pid: Int\n public let bundle: String\n public var annotations: [String: String]?\n}\n\npublic let seccompFdName: String = \"seccompFd\"\n\npublic struct ContainerProcessState: Codable, Sendable {\n public init(version: String, fds: [String], pid: Int, metadata: String, state: State) {\n self.ociVersion = version\n self.fds = fds\n self.pid = pid\n self.metadata = metadata\n self.state = state\n }\n\n public init(instance: ContainerProcessState) {\n self.ociVersion = instance.ociVersion\n self.fds = instance.fds\n self.pid = instance.pid\n self.metadata = instance.metadata\n self.state = instance.state\n }\n\n public let ociVersion: String\n public var fds: [String]\n public let pid: Int\n public let metadata: String\n public let state: State\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Types.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// swiftlint:disable large_tuple\n\nimport Foundation\n\nextension EXT4 {\n public struct SuperBlock {\n public var inodesCount: UInt32 = 0\n public var blocksCountLow: UInt32 = 0\n public var rootBlocksCountLow: UInt32 = 0\n public var freeBlocksCountLow: UInt32 = 0\n public var freeInodesCount: UInt32 = 0\n public var firstDataBlock: UInt32 = 0\n public var logBlockSize: UInt32 = 0\n public var logClusterSize: UInt32 = 0\n public var blocksPerGroup: UInt32 = 0\n public var clustersPerGroup: UInt32 = 0\n public var inodesPerGroup: UInt32 = 0\n public var mtime: UInt32 = 0\n public var wtime: UInt32 = 0\n public var mountCount: UInt16 = 0\n public var maxMountCount: UInt16 = 0\n public var magic: UInt16 = 0\n public var state: UInt16 = 0\n public var errors: UInt16 = 0\n public var minorRevisionLevel: UInt16 = 0\n public var lastCheck: UInt32 = 0\n public var checkInterval: UInt32 = 0\n public var creatorOS: UInt32 = 0\n public var revisionLevel: UInt32 = 0\n public var defaultReservedUid: UInt16 = 0\n public var defaultReservedGid: UInt16 = 0\n public var firstInode: UInt32 = 0\n public var inodeSize: UInt16 = 0\n public var blockGroupNr: UInt16 = 0\n public var featureCompat: UInt32 = 0\n public var featureIncompat: UInt32 = 0\n public var featureRoCompat: UInt32 = 0\n public var uuid:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var volumeName:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var lastMounted:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var algorithmUsageBitmap: UInt32 = 0\n public var preallocBlocks: UInt8 = 0\n public var preallocDirBlocks: UInt8 = 0\n public var reservedGdtBlocks: UInt16 = 0\n public var journalUUID:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var journalInum: UInt32 = 0\n public var journalDev: UInt32 = 0\n public var lastOrphan: UInt32 = 0\n public var hashSeed: (UInt32, UInt32, UInt32, UInt32) = (0, 0, 0, 0)\n public var defHashVersion: UInt8 = 0\n public var journalBackupType: UInt8 = 0\n public var descSize: UInt16 = UInt16(MemoryLayout.size)\n public var defaultMountOpts: UInt32 = 0\n public var firstMetaBg: UInt32 = 0\n public var mkfsTime: UInt32 = 0\n public var journalBlocks:\n (\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0\n )\n public var blocksCountHigh: UInt32 = 0\n public var rBlocksCountHigh: UInt32 = 0\n public var freeBlocksCountHigh: UInt32 = 0\n public var minExtraIsize: UInt16 = 0\n public var wantExtraIsize: UInt16 = 0\n public var flags: UInt32 = 0\n public var raidStride: UInt16 = 0\n public var mmpInterval: UInt16 = 0\n public var mmpBlock: UInt64 = 0\n public var raidStripeWidth: UInt32 = 0\n public var logGroupsPerFlex: UInt8 = 0\n public var checksumType: UInt8 = 0\n public var reservedPad: UInt16 = 0\n public var kbytesWritten: UInt64 = 0\n public var snapshotInum: UInt32 = 0\n public var snapshotID: UInt32 = 0\n public var snapshotRBlocksCount: UInt64 = 0\n public var snapshotList: UInt32 = 0\n public var errorCount: UInt32 = 0\n public var firstErrorTime: UInt32 = 0\n public var firstErrorInode: UInt32 = 0\n public var firstErrorBlock: UInt64 = 0\n public var firstErrorFunc:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var firstErrorLine: UInt32 = 0\n public var lastErrorTime: UInt32 = 0\n public var lastErrorInode: UInt32 = 0\n public var lastErrorLine: UInt32 = 0\n public var lastErrorBlock: UInt64 = 0\n public var lastErrorFunc:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var mountOpts:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var userQuotaInum: UInt32 = 0\n public var groupQuotaInum: UInt32 = 0\n public var overheadBlocks: UInt32 = 0\n public var backupBgs: (UInt32, UInt32) = (0, 0)\n public var encryptAlgos: (UInt8, UInt8, UInt8, UInt8) = (0, 0, 0, 0)\n public var encryptPwSalt:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var lpfInode: UInt32 = 0\n public var projectQuotaInum: UInt32 = 0\n public var checksumSeed: UInt32 = 0\n public var wtimeHigh: UInt8 = 0\n public var mtimeHigh: UInt8 = 0\n public var mkfsTimeHigh: UInt8 = 0\n public var lastcheckHigh: UInt8 = 0\n public var firstErrorTimeHigh: UInt8 = 0\n public var lastErrorTimeHigh: UInt8 = 0\n public var pad: (UInt8, UInt8) = (0, 0)\n public var reserved:\n (\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var checksum: UInt32 = 0\n }\n\n struct CompatFeature {\n let rawValue: UInt32\n\n static let dirPrealloc = CompatFeature(rawValue: 0x1)\n static let imagicInodes = CompatFeature(rawValue: 0x2)\n static let hasJournal = CompatFeature(rawValue: 0x4)\n static let extAttr = CompatFeature(rawValue: 0x8)\n static let resizeInode = CompatFeature(rawValue: 0x10)\n static let dirIndex = CompatFeature(rawValue: 0x20)\n static let lazyBg = CompatFeature(rawValue: 0x40)\n static let excludeInode = CompatFeature(rawValue: 0x80)\n static let excludeBitmap = CompatFeature(rawValue: 0x100)\n static let sparseSuper2 = CompatFeature(rawValue: 0x200)\n }\n\n struct IncompatFeature {\n let rawValue: UInt32\n\n static let compression = IncompatFeature(rawValue: 0x1)\n static let filetype = IncompatFeature(rawValue: 0x2)\n static let recover = IncompatFeature(rawValue: 0x4)\n static let journalDev = IncompatFeature(rawValue: 0x8)\n static let metaBg = IncompatFeature(rawValue: 0x10)\n static let extents = IncompatFeature(rawValue: 0x40)\n static let bit64 = IncompatFeature(rawValue: 0x80)\n static let mmp = IncompatFeature(rawValue: 0x100)\n static let flexBg = IncompatFeature(rawValue: 0x200)\n static let eaInode = IncompatFeature(rawValue: 0x400)\n static let dirdata = IncompatFeature(rawValue: 0x1000)\n static let csumSeed = IncompatFeature(rawValue: 0x2000)\n static let largedir = IncompatFeature(rawValue: 0x4000)\n static let inlineData = IncompatFeature(rawValue: 0x8000)\n static let encrypt = IncompatFeature(rawValue: 0x10000)\n }\n\n struct RoCompatFeature {\n let rawValue: UInt32\n\n static let sparseSuper = RoCompatFeature(rawValue: 0x1)\n static let largeFile = RoCompatFeature(rawValue: 0x2)\n static let btreeDir = RoCompatFeature(rawValue: 0x4)\n static let hugeFile = RoCompatFeature(rawValue: 0x8)\n static let gdtCsum = RoCompatFeature(rawValue: 0x10)\n static let dirNlink = RoCompatFeature(rawValue: 0x20)\n static let extraIsize = RoCompatFeature(rawValue: 0x40)\n static let hasSnapshot = RoCompatFeature(rawValue: 0x80)\n static let quota = RoCompatFeature(rawValue: 0x100)\n static let bigalloc = RoCompatFeature(rawValue: 0x200)\n static let metadataCsum = RoCompatFeature(rawValue: 0x400)\n static let replica = RoCompatFeature(rawValue: 0x800)\n static let readonly = RoCompatFeature(rawValue: 0x1000)\n static let project = RoCompatFeature(rawValue: 0x2000)\n }\n\n struct BlockGroupFlag {\n let rawValue: UInt16\n\n static let inodeUninit = BlockGroupFlag(rawValue: 0x1)\n static let blockUninit = BlockGroupFlag(rawValue: 0x2)\n static let inodeZeroed = BlockGroupFlag(rawValue: 0x4)\n }\n\n struct GroupDescriptor {\n let blockBitmapLow: UInt32\n let inodeBitmapLow: UInt32\n let inodeTableLow: UInt32\n let freeBlocksCountLow: UInt16\n let freeInodesCountLow: UInt16\n let usedDirsCountLow: UInt16\n let flags: UInt16\n let excludeBitmapLow: UInt32\n let blockBitmapCsumLow: UInt16\n let inodeBitmapCsumLow: UInt16\n let itableUnusedLow: UInt16\n let checksum: UInt16\n }\n\n struct GroupDescriptor64 {\n let groupDescriptor: GroupDescriptor\n let blockBitmapHigh: UInt32\n let inodeBitmapHigh: UInt32\n let inodeTableHigh: UInt32\n let freeBlocksCountHigh: UInt16\n let freeInodesCountHigh: UInt16\n let usedDirsCountHigh: UInt16\n let itableUnusedHigh: UInt16\n let excludeBitmapHigh: UInt32\n let blockBitmapCsumHigh: UInt16\n let inodeBitmapCsumHigh: UInt16\n let reserved: UInt32\n }\n\n public struct FileModeFlag: Sendable {\n let rawValue: UInt16\n\n public static let S_IXOTH = FileModeFlag(rawValue: 0x1)\n public static let S_IWOTH = FileModeFlag(rawValue: 0x2)\n public static let S_IROTH = FileModeFlag(rawValue: 0x4)\n public static let S_IXGRP = FileModeFlag(rawValue: 0x8)\n public static let S_IWGRP = FileModeFlag(rawValue: 0x10)\n public static let S_IRGRP = FileModeFlag(rawValue: 0x20)\n public static let S_IXUSR = FileModeFlag(rawValue: 0x40)\n public static let S_IWUSR = FileModeFlag(rawValue: 0x80)\n public static let S_IRUSR = FileModeFlag(rawValue: 0x100)\n public static let S_ISVTX = FileModeFlag(rawValue: 0x200)\n public static let S_ISGID = FileModeFlag(rawValue: 0x400)\n public static let S_ISUID = FileModeFlag(rawValue: 0x800)\n public static let S_IFIFO = FileModeFlag(rawValue: 0x1000)\n public static let S_IFCHR = FileModeFlag(rawValue: 0x2000)\n public static let S_IFDIR = FileModeFlag(rawValue: 0x4000)\n public static let S_IFBLK = FileModeFlag(rawValue: 0x6000)\n public static let S_IFREG = FileModeFlag(rawValue: 0x8000)\n public static let S_IFLNK = FileModeFlag(rawValue: 0xA000)\n public static let S_IFSOCK = FileModeFlag(rawValue: 0xC000)\n\n public static let TypeMask = FileModeFlag(rawValue: 0xF000)\n }\n\n typealias InodeNumber = UInt32\n\n public struct Inode {\n var mode: UInt16 = 0\n var uid: UInt16 = 0\n var sizeLow: UInt32 = 0\n var atime: UInt32 = 0\n var ctime: UInt32 = 0\n var mtime: UInt32 = 0\n var dtime: UInt32 = 0\n var gid: UInt16 = 0\n var linksCount: UInt16 = 0\n var blocksLow: UInt32 = 0\n var flags: UInt32 = 0\n var version: UInt32 = 0\n var block:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n )\n var generation: UInt32 = 0\n var xattrBlockLow: UInt32 = 0\n var sizeHigh: UInt32 = 0\n var obsoleteFragmentAddr: UInt32 = 0\n var blocksHigh: UInt16 = 0\n var xattrBlockHigh: UInt16 = 0\n var uidHigh: UInt16 = 0\n var gidHigh: UInt16 = 0\n var checksumLow: UInt16 = 0\n var reserved: UInt16 = 0\n var extraIsize: UInt16 = 0\n var checksumHigh: UInt16 = 0\n var ctimeExtra: UInt32 = 0\n var mtimeExtra: UInt32 = 0\n var atimeExtra: UInt32 = 0\n var crtime: UInt32 = 0\n var crtimeExtra: UInt32 = 0\n var versionHigh: UInt32 = 0\n var projid: UInt32 = 0 // Size until this point is 160 bytes\n var inlineXattrs:\n ( // 96 bytes for extended attributes\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0\n )\n\n public static func Mode(_ mode: FileModeFlag, _ perm: UInt16) -> UInt16 {\n mode.rawValue | perm\n }\n }\n\n struct InodeFlag {\n let rawValue: UInt32\n\n static let secRm = InodeFlag(rawValue: 0x1)\n static let unRm = InodeFlag(rawValue: 0x2)\n static let compressed = InodeFlag(rawValue: 0x4)\n static let sync = InodeFlag(rawValue: 0x8)\n static let immutable = InodeFlag(rawValue: 0x10)\n static let append = InodeFlag(rawValue: 0x20)\n static let noDump = InodeFlag(rawValue: 0x40)\n static let noAtime = InodeFlag(rawValue: 0x80)\n static let dirtyCompressed = InodeFlag(rawValue: 0x100)\n static let compressedClusters = InodeFlag(rawValue: 0x200)\n static let noCompress = InodeFlag(rawValue: 0x400)\n static let encrypted = InodeFlag(rawValue: 0x800)\n static let hashedIndex = InodeFlag(rawValue: 0x1000)\n static let magic = InodeFlag(rawValue: 0x2000)\n static let journalData = InodeFlag(rawValue: 0x4000)\n static let noTail = InodeFlag(rawValue: 0x8000)\n static let dirSync = InodeFlag(rawValue: 0x10000)\n static let topDir = InodeFlag(rawValue: 0x20000)\n static let hugeFile = InodeFlag(rawValue: 0x40000)\n static let extents = InodeFlag(rawValue: 0x80000)\n static let eaInode = InodeFlag(rawValue: 0x200000)\n static let eofBlocks = InodeFlag(rawValue: 0x400000)\n static let snapfile = InodeFlag(rawValue: 0x0100_0000)\n static let snapfileDeleted = InodeFlag(rawValue: 0x0400_0000)\n static let snapfileShrunk = InodeFlag(rawValue: 0x0800_0000)\n static let inlineData = InodeFlag(rawValue: 0x1000_0000)\n static let projectIDInherit = InodeFlag(rawValue: 0x2000_0000)\n static let reserved = InodeFlag(rawValue: 0x8000_0000)\n }\n\n struct ExtentHeader {\n let magic: UInt16\n let entries: UInt16\n let max: UInt16\n let depth: UInt16\n let generation: UInt32\n }\n\n struct ExtentIndex {\n let block: UInt32\n let leafLow: UInt32\n let leafHigh: UInt16\n let unused: UInt16\n }\n\n struct ExtentLeaf {\n let block: UInt32\n let length: UInt16\n let startHigh: UInt16\n let startLow: UInt32\n }\n\n struct ExtentTail {\n let checksum: UInt32\n }\n\n struct ExtentIndexNode {\n var header: ExtentHeader\n var indices: [ExtentIndex]\n }\n\n struct ExtentLeafNode {\n var header: ExtentHeader\n var leaves: [ExtentLeaf]\n }\n\n struct DirectoryEntry {\n let inode: InodeNumber\n let recordLength: UInt16\n let nameLength: UInt8\n let fileType: UInt8\n // let name: [UInt8]\n }\n\n enum FileType: UInt8 {\n case unknown = 0x0\n case regular = 0x1\n case directory = 0x2\n case character = 0x3\n case block = 0x4\n case fifo = 0x5\n case socket = 0x6\n case symbolicLink = 0x7\n }\n\n struct DirectoryEntryTail {\n let reservedZero1: UInt32\n let recordLength: UInt16\n let reservedZero2: UInt8\n let fileType: UInt8\n let checksum: UInt32\n }\n\n struct DirectoryTreeRoot {\n let dot: DirectoryEntry\n let dotName: [UInt8]\n let dotDot: DirectoryEntry\n let dotDotName: [UInt8]\n let reservedZero: UInt32\n let hashVersion: UInt8\n let infoLength: UInt8\n let indirectLevels: UInt8\n let unusedFlags: UInt8\n let limit: UInt16\n let count: UInt16\n let block: UInt32\n // let entries: [DirectoryTreeEntry]\n }\n\n struct DirectoryTreeNode {\n let fakeInode: UInt32\n let fakeRecordLength: UInt16\n let nameLength: UInt8\n let fileType: UInt8\n let limit: UInt16\n let count: UInt16\n let block: UInt32\n // let entries: [DirectoryTreeEntry]\n }\n\n struct DirectoryTreeEntry {\n let hash: UInt32\n let block: UInt32\n }\n\n struct DirectoryTreeTail {\n let reserved: UInt32\n let checksum: UInt32\n }\n\n struct XAttrEntry {\n let nameLength: UInt8\n let nameIndex: UInt8\n let valueOffset: UInt16\n let valueInum: UInt32\n let valueSize: UInt32\n let hash: UInt32\n }\n\n struct XAttrHeader {\n let magic: UInt32\n let referenceCount: UInt32\n let blocks: UInt32\n let hash: UInt32\n let checksum: UInt32\n let reserved: [UInt32]\n }\n\n}\n\nextension EXT4.Inode {\n public static func Root() -> EXT4.Inode {\n var inode = Self() // inode\n inode.mode = Self.Mode(.S_IFDIR, 0o755)\n inode.linksCount = 2\n inode.uid = 0\n inode.gid = 0\n // time\n let now = Date().fs()\n let now_lo: UInt32 = now.lo\n let now_hi: UInt32 = now.hi\n inode.atime = now_lo\n inode.atimeExtra = now_hi\n inode.ctime = now_lo\n inode.ctimeExtra = now_hi\n inode.mtime = now_lo\n inode.mtimeExtra = now_hi\n inode.crtime = now_lo\n inode.crtimeExtra = now_hi\n inode.flags = EXT4.InodeFlag.hugeFile.rawValue\n inode.extraIsize = UInt16(EXT4.ExtraIsize)\n return inode\n }\n}\n"], ["/containerization/vminitd/Sources/vmexec/Mount.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Musl\n\nstruct ContainerMount {\n private let mounts: [ContainerizationOCI.Mount]\n private let rootfs: String\n\n init(rootfs: String, mounts: [ContainerizationOCI.Mount]) {\n self.rootfs = rootfs\n self.mounts = mounts\n }\n\n func mountToRootfs() throws {\n for m in self.mounts {\n let osMount = m.toOSMount()\n try osMount.mount(root: self.rootfs)\n }\n }\n\n func configureConsole() throws {\n let ptmx = self.rootfs.standardizingPath.appendingPathComponent(\"/dev/ptmx\")\n\n guard remove(ptmx) == 0 else {\n throw App.Errno(stage: \"remove(ptmx)\")\n }\n guard symlink(\"pts/ptmx\", ptmx) == 0 else {\n throw App.Errno(stage: \"symlink(pts/ptmx)\")\n }\n }\n\n private func mkdirAll(_ name: String, _ perm: Int16) throws {\n try FileManager.default.createDirectory(\n atPath: name,\n withIntermediateDirectories: true,\n attributes: [.posixPermissions: perm]\n )\n }\n}\n\nextension ContainerizationOCI.Mount {\n func toOSMount() -> ContainerizationOS.Mount {\n ContainerizationOS.Mount(\n type: self.type,\n source: self.source,\n target: self.destination,\n options: self.options\n )\n }\n}\n"], ["/containerization/Sources/Containerization/UnixSocketConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\n/// Represents a UnixSocket that can be shared into or out of a container/guest.\npublic struct UnixSocketConfiguration: Sendable {\n // TODO: Realistically, we can just hash this struct and use it as the \"id\".\n package var id: String {\n _id\n }\n\n private let _id = UUID().uuidString\n\n /// The path to the socket you'd like relayed. For .into\n /// direction this should be the path on the host to a unix socket.\n /// For direction .outOf this should be the path in the container/guest\n /// to a unix socket.\n public var source: URL\n\n /// The path you'd like the socket to be relayed to. For .into\n /// direction this should be the path in the container/guest. For\n /// direction .outOf this should be the path on your host.\n public var destination: URL\n\n /// What to set the file permissions of the unix socket being created\n /// to. For .into direction this will be the socket in the guest. For\n /// .outOf direction this will be the socket on the host.\n public var permissions: FilePermissions?\n\n /// The direction of the relay. `.into` for sharing a unix socket on your\n /// host into the container/guest. `outOf` shares a socket in the container/guest\n /// onto your host.\n public var direction: Direction\n\n /// Type that denotes the direction of the unix socket relay.\n public enum Direction: Sendable {\n /// Share the socket into the container/guest.\n case into\n /// Share a socket in the container/guest onto the host.\n case outOf\n }\n\n public init(\n source: URL,\n destination: URL,\n permissions: FilePermissions? = nil,\n direction: Direction = .into\n ) {\n self.source = source\n self.destination = destination\n self.permissions = permissions\n self.direction = direction\n }\n}\n"], ["/containerization/Sources/Containerization/DNSConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// DNS configuration for a container. The values will be used to\n/// construct /etc/resolv.conf for a given container.\npublic struct DNS: Sendable {\n /// The set of default nameservers to use if none are provided\n /// in the constructor.\n public static let defaultNameservers = [\"1.1.1.1\"]\n\n /// The nameservers a container should use.\n public var nameservers: [String]\n /// The DNS domain to use.\n public var domain: String?\n /// The DNS search domains to use.\n public var searchDomains: [String]\n /// The DNS options to use.\n public var options: [String]\n\n public init(\n nameservers: [String] = defaultNameservers,\n domain: String? = nil,\n searchDomains: [String] = [],\n options: [String] = []\n ) {\n self.nameservers = nameservers\n self.domain = domain\n self.searchDomains = searchDomains\n self.options = options\n }\n}\n\nextension DNS {\n public var resolvConf: String {\n var text = \"\"\n\n if !nameservers.isEmpty {\n text += nameservers.map { \"nameserver \\($0)\" }.joined(separator: \"\\n\") + \"\\n\"\n }\n\n if let domain {\n text += \"domain \\(domain)\\n\"\n }\n\n if !searchDomains.isEmpty {\n text += \"search \\(searchDomains.joined(separator: \" \"))\\n\"\n }\n\n if !options.isEmpty {\n text += \"opts \\(options.joined(separator: \" \"))\\n\"\n }\n\n return text\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/FileArchiveWriterDelegate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\ninternal final class FileArchiveWriterDelegate {\n public let path: FilePath\n private var fd: FileDescriptor!\n\n public init(path: FilePath) {\n self.path = path\n }\n\n public convenience init(url: URL) {\n self.init(path: FilePath(url.path))\n }\n\n public func open(archive: ArchiveWriter) throws {\n self.fd = try FileDescriptor.open(\n self.path, .writeOnly, options: [.create, .append], permissions: [.groupRead, .otherRead, .ownerReadWrite])\n }\n\n public func write(archive: ArchiveWriter, buffer: UnsafeRawBufferPointer) throws -> Int {\n try fd.write(buffer)\n }\n\n public func close(archive: ArchiveWriter) throws {\n try self.fd.close()\n }\n\n public func free(archive: ArchiveWriter) {\n self.fd = nil\n }\n\n deinit {\n if let fd = self.fd {\n try? fd.close()\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Ptr.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension EXT4 {\n class Ptr {\n let underlying: UnsafeMutablePointer\n private var capacity: Int\n private var initialized: Bool\n private var allocated: Bool\n\n var pointee: T {\n underlying.pointee\n }\n\n init(capacity: Int) {\n self.underlying = UnsafeMutablePointer.allocate(capacity: capacity)\n self.capacity = capacity\n self.allocated = true\n self.initialized = false\n }\n\n static func allocate(capacity: Int) -> Ptr {\n Ptr(capacity: capacity)\n }\n\n func initialize(to value: T) {\n guard self.allocated else {\n return\n }\n if self.initialized {\n self.underlying.deinitialize(count: self.capacity)\n }\n self.underlying.initialize(to: value)\n self.allocated = true\n self.initialized = true\n }\n\n func deallocate() {\n guard self.allocated else {\n return\n }\n self.underlying.deallocate()\n self.allocated = false\n self.initialized = false\n }\n\n func deinitialize(count: Int) {\n guard self.allocated else {\n return\n }\n guard self.initialized else {\n return\n }\n self.underlying.deinitialize(count: count)\n self.initialized = false\n self.allocated = true\n }\n\n func move() -> T {\n self.initialized = false\n self.allocated = true\n return self.underlying.move()\n }\n\n deinit {\n self.deinitialize(count: self.capacity)\n self.deallocate()\n }\n }\n}\n"], ["/containerization/Sources/Containerization/VirtualMachineInstance.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// The runtime state of the virtual machine instance.\npublic enum VirtualMachineInstanceState: Sendable {\n case starting\n case running\n case stopped\n case stopping\n case unknown\n}\n\n/// A live instance of a virtual machine.\npublic protocol VirtualMachineInstance: Sendable {\n associatedtype Agent: VirtualMachineAgent\n\n // The state of the virtual machine.\n var state: VirtualMachineInstanceState { get }\n\n var mounts: [AttachedFilesystem] { get }\n /// Dial the Agent. It's up the VirtualMachineInstance to determine\n /// what port the agent is listening on.\n func dialAgent() async throws -> Agent\n /// Dial a vsock port in the guest.\n func dial(_ port: UInt32) async throws -> FileHandle\n /// Listen on a host vsock port.\n func listen(_ port: UInt32) throws -> VsockConnectionStream\n /// Stop listening on a vsock port.\n func stopListen(_ port: UInt32) throws\n /// Start the virtual machine.\n func start() async throws\n /// Stop the virtual machine.\n func stop() async throws\n}\n"], ["/containerization/Sources/SendableProperty/Synchronized.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// `Synchronization` will be automatically imported with `SendableProperty`.\n@_exported import Synchronization\n\n/// A synchronization primitive that protects shared mutable state via mutual exclusion.\npublic final class Synchronized: Sendable {\n private let lock: Mutex\n\n private struct State: @unchecked Sendable {\n var value: T\n }\n\n /// Creates a new instance.\n /// - Parameter value: The initial value.\n public init(_ value: T) {\n self.lock = Mutex(State(value: value))\n }\n\n /// Calls the given closure after acquiring the lock and returns its value.\n /// - Parameter body: The body of code to execute while the lock is held.\n public func withLock(_ body: (inout T) throws -> R) rethrows -> R {\n try lock.withLock { state in\n try body(&state.value)\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/UnsafeLittleEndianBytes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n// takes a pointer and converts its contents to native endian bytes\npublic func withUnsafeLittleEndianBytes(of value: T, body: (UnsafeRawBufferPointer) throws -> Result)\n rethrows -> Result\n{\n switch Endian {\n case .little:\n return try withUnsafeBytes(of: value) { bytes in\n try body(bytes)\n }\n case .big:\n return try withUnsafeBytes(of: value) { buffer in\n let reversedBuffer = Array(buffer.reversed())\n return try reversedBuffer.withUnsafeBytes { buf in\n try body(buf)\n }\n }\n }\n}\n\npublic func withUnsafeLittleEndianBuffer(\n of value: UnsafeRawBufferPointer, body: (UnsafeRawBufferPointer) throws -> T\n) rethrows -> T {\n switch Endian {\n case .little:\n return try body(value)\n case .big:\n let reversed = Array(value.reversed())\n return try reversed.withUnsafeBytes { buf in\n try body(buf)\n }\n }\n}\n\nextension UnsafeRawBufferPointer {\n // loads littleEndian raw data, converts it native endian format and calls UnsafeRawBufferPointer.load\n public func loadLittleEndian(as type: T.Type) -> T {\n switch Endian {\n case .little:\n return self.load(as: T.self)\n case .big:\n let buffer = Array(self.reversed())\n return buffer.withUnsafeBytes { ptr in\n ptr.load(as: T.self)\n }\n }\n }\n}\n\npublic enum Endianness {\n case little\n case big\n}\n\n// returns current endianness\npublic var Endian: Endianness {\n switch CFByteOrderGetCurrent() {\n case CFByteOrder(CFByteOrderLittleEndian.rawValue):\n return .little\n case CFByteOrder(CFByteOrderBigEndian.rawValue):\n return .big\n default:\n fatalError(\"impossible\")\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/FileManager+Size.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension FileManager {\n func fileSize(atPath path: String) -> Int64? {\n do {\n let attributes = try attributesOfItem(atPath: path)\n guard let fileSize = attributes[.size] as? NSNumber else {\n return nil\n }\n return fileSize.int64Value\n } catch {\n return nil\n }\n }\n}\n"], ["/containerization/Sources/Containerization/AttachedFilesystem.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport ContainerizationOCI\n\n/// A filesystem that was attached and able to be mounted inside the runtime environment.\npublic struct AttachedFilesystem: Sendable {\n /// The type of the filesystem.\n public var type: String\n /// The path to the filesystem within a sandbox.\n public var source: String\n /// Destination when mounting the filesystem inside a sandbox.\n public var destination: String\n /// The options to use when mounting the filesystem.\n public var options: [String]\n\n #if os(macOS)\n public init(mount: Mount, allocator: any AddressAllocator) throws {\n switch mount.type {\n case \"virtiofs\":\n let name = try hashMountSource(source: mount.source)\n self.source = name\n case \"ext4\":\n let char = try allocator.allocate()\n self.source = \"/dev/vd\\(char)\"\n default:\n self.source = mount.source\n }\n self.type = mount.type\n self.options = mount.options\n self.destination = mount.destination\n }\n #endif\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/ContentStoreProtocol.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Crypto\nimport Foundation\n\n/// Protocol for defining a content store where OCI image metadata and layers will be managed\n/// and manipulated.\npublic protocol ContentStore: Sendable {\n /// Retrieves a piece of Content based on the digest string.\n /// Returns `nil` if the requested digest is not found.\n func get(digest: String) async throws -> Content?\n\n /// Retrieves a specific content metadata type based on the digest string.\n /// Returns `nil` if the requested digest is not found.\n func get(digest: String) async throws -> T?\n\n /// Remove a list of digests in the content store.\n @discardableResult\n func delete(digests: [String]) async throws -> ([String], UInt64)\n\n /// Removes all content from the store except for the digests in the provided list.\n @discardableResult\n func delete(keeping: [String]) async throws -> ([String], UInt64)\n\n /// Creates a transactional write to the content store.\n /// The function takes a closure given a temporary `URL` of the base directory which all contents should be written to.\n /// This is transaction write where any failed operation in the closure (caught exception) will result in all contents written\n /// in the closure to be deleted.\n ///\n /// If the closure succeeds, then all the content that have been written to the temporary `URL` will be moved into the actual\n /// blobs path of the content store.\n @discardableResult\n func ingest(_ body: @Sendable @escaping (URL) async throws -> Void) async throws -> [String]\n\n /// Creates a new ingest session and returns the session ID and temporary ingest directory corresponding to the session.\n /// The contents from the ingest directory are processed and moved into the content store once the session is marked complete.\n /// This can be done by invoking the `completeIngestSession` method with the returned session ID.\n func newIngestSession() async throws -> (id: String, ingestDir: URL)\n\n /// Completes a previously started ingest session corresponding to `id`.\n /// The contents from the ingest directory from the session are moved into the content store atomically.\n /// Any failure encountered will result in a transaction failure causing none of the contents to be ingested into the store.\n @discardableResult\n func completeIngestSession(_ id: String) async throws -> [String]\n\n /// Cancels a previously started ingest session corresponding to `id`.\n /// The contents from the ingest directory corresponding to the session are removed.\n func cancelIngestSession(_ id: String) async throws\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension EXT4.InodeFlag {\n public static func | (lhs: Self, rhs: Self) -> Self {\n Self(rawValue: lhs.rawValue | rhs.rawValue)\n }\n\n public static func | (lhs: Self, rhs: Self) -> UInt32 {\n lhs.rawValue | rhs.rawValue\n }\n\n public static func | (lhs: Self, rhs: UInt32) -> UInt32 {\n lhs.rawValue | rhs\n }\n}\n\nextension EXT4.CompatFeature {\n public static func | (lhs: Self, rhs: Self) -> Self {\n EXT4.CompatFeature(rawValue: lhs.rawValue | rhs.rawValue)\n }\n\n public static func | (lhs: Self, rhs: Self) -> UInt32 {\n lhs.rawValue | rhs.rawValue\n }\n}\n\nextension EXT4.IncompatFeature {\n public static func | (lhs: Self, rhs: Self) -> Self {\n EXT4.IncompatFeature(rawValue: lhs.rawValue | rhs.rawValue)\n }\n\n public static func | (lhs: Self, rhs: Self) -> UInt32 {\n lhs.rawValue | rhs.rawValue\n }\n}\n\nextension EXT4.RoCompatFeature {\n public static func | (lhs: Self, rhs: Self) -> Self {\n EXT4.RoCompatFeature(rawValue: lhs.rawValue | rhs.rawValue)\n }\n\n public static func | (lhs: Self, rhs: Self) -> UInt32 {\n lhs.rawValue | rhs.rawValue\n }\n}\n\nextension EXT4.FileModeFlag {\n public static func | (lhs: Self, rhs: Self) -> Self {\n Self(rawValue: lhs.rawValue | rhs.rawValue)\n }\n\n public static func | (lhs: Self, rhs: Self) -> UInt16 {\n lhs.rawValue | rhs.rawValue\n }\n}\n\nextension EXT4.XAttrEntry {\n init(using bytes: [UInt8]) throws {\n guard bytes.count == 16 else {\n throw EXT4.Error.invalidXattrEntry\n }\n nameLength = bytes[0]\n nameIndex = bytes[1]\n let rawValue = Array(bytes[2...3])\n valueOffset = UInt16(littleEndian: rawValue.withUnsafeBytes { $0.load(as: UInt16.self) })\n\n let rawValueInum = Array(bytes[4...7])\n valueInum = UInt32(littleEndian: rawValueInum.withUnsafeBytes { $0.load(as: UInt32.self) })\n\n let rawSize = Array(bytes[8...11])\n valueSize = UInt32(littleEndian: rawSize.withUnsafeBytes { $0.load(as: UInt32.self) })\n\n let rawHash = Array(bytes[12...])\n hash = UInt32(littleEndian: rawHash.withUnsafeBytes { $0.load(as: UInt32.self) })\n }\n}\n\nextension EXT4 {\n static func tupleToArray(_ tuple: T) -> [UInt8] {\n let reflection = Mirror(reflecting: tuple)\n return reflection.children.compactMap { $0.value as? UInt8 }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/Authentication.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Abstraction for returning a token needed for logging into an OCI compliant registry.\npublic protocol Authentication: Sendable {\n func token() async throws -> String\n}\n\n/// Type representing authentication information for client to access the registry.\npublic struct BasicAuthentication: Authentication {\n /// The username for the authentication.\n let username: String\n /// The password or identity token for the user.\n let password: String\n\n public init(username: String, password: String) {\n self.username = username\n self.password = password\n }\n\n /// Get a token using the provided username and password. This will be a\n /// base64 encoded string of the username and password delimited by a colon.\n public func token() async throws -> String {\n let credentials = \"\\(username):\\(password)\"\n if let authenticationData = credentials.data(using: .utf8)?.base64EncodedString() {\n return \"Basic \\(authenticationData)\"\n }\n throw Error.invalidCredentials\n }\n\n /// `BasicAuthentication` errors.\n public enum Error: Swift.Error {\n case invalidCredentials\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/NetworkAddress.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Errors related to IP and CIDR addresses.\npublic enum NetworkAddressError: Swift.Error, Equatable, CustomStringConvertible {\n case invalidStringAddress(address: String)\n case invalidNetworkByteAddress(address: [UInt8])\n case invalidCIDR(cidr: String)\n case invalidAddressForSubnet(address: String, cidr: String)\n case invalidAddressRange(lower: String, upper: String)\n\n public var description: String {\n switch self {\n case .invalidStringAddress(let address):\n return \"invalid IP address string \\(address)\"\n case .invalidNetworkByteAddress(let address):\n return \"invalid IP address bytes \\(address)\"\n case .invalidCIDR(let cidr):\n return \"invalid CIDR block: \\(cidr)\"\n case .invalidAddressForSubnet(let address, let cidr):\n return \"invalid address \\(address) for subnet \\(cidr)\"\n case .invalidAddressRange(let lower, let upper):\n return \"invalid range for addresses \\(lower) and \\(upper)\"\n }\n }\n}\n\npublic typealias PrefixLength = UInt8\n\nextension PrefixLength {\n /// Compute a bit mask that passes the suffix bits, given the network prefix mask length.\n public var suffixMask32: UInt32 {\n if self <= 0 {\n return 0xffff_ffff\n }\n return self >= 32 ? 0x0000_0000 : (1 << (32 - self)) - 1\n }\n\n /// Compute a bit mask that passes the prefix bits, given the network prefix mask length.\n public var prefixMask32: UInt32 {\n ~self.suffixMask32\n }\n\n /// Compute a bit mask that passes the suffix bits, given the network prefix mask length.\n public var suffixMask48: UInt64 {\n if self <= 0 {\n return 0x0000_ffff_ffff_ffff\n }\n return self >= 48 ? 0x0000_0000_0000_0000 : (1 << (48 - self)) - 1\n }\n\n /// Compute a bit mask that passes the prefix bits, given the network prefix mask length.\n public var prefixMask48: UInt64 {\n ~self.suffixMask48 & 0x0000_ffff_ffff_ffff\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Manifest.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// Source: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/manifest.go\n\nimport Foundation\n\n/// Manifest provides `application/vnd.oci.image.manifest.v1+json` mediatype structure when marshalled to JSON.\npublic struct Manifest: Codable, Sendable {\n /// `schemaVersion` is the image manifest schema that this image follows.\n public let schemaVersion: Int\n\n /// `mediaType` specifies the type of this document data structure, e.g. `application/vnd.oci.image.manifest.v1+json`.\n public let mediaType: String?\n\n /// `config` references a configuration object for a container, by digest.\n /// The referenced configuration object is a JSON blob that the runtime uses to set up the container.\n public let config: Descriptor\n\n /// `layers` is an indexed list of layers referenced by the manifest.\n public let layers: [Descriptor]\n\n /// `annotations` contains arbitrary metadata for the image manifest.\n public let annotations: [String: String]?\n\n public init(\n schemaVersion: Int = 2, mediaType: String = MediaTypes.imageManifest, config: Descriptor, layers: [Descriptor],\n annotations: [String: String]? = nil\n ) {\n self.schemaVersion = schemaVersion\n self.mediaType = mediaType\n self.config = config\n self.layers = layers\n self.annotations = annotations\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/HostStdio.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nstruct HostStdio: Sendable {\n let stdin: UInt32?\n let stdout: UInt32?\n let stderr: UInt32?\n let terminal: Bool\n}\n"], ["/containerization/Sources/ContainerizationOS/Syscall.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if canImport(Musl)\nimport Musl\n#elseif canImport(Glibc)\nimport Glibc\n#elseif canImport(Darwin)\nimport Darwin\n#else\n#error(\"retryingSyscall not supported on this platform.\")\n#endif\n\n/// Helper type to deal with running system calls.\npublic struct Syscall {\n /// Retry a syscall on EINTR.\n public static func retrying(_ closure: () -> T) -> T {\n while true {\n let res = closure()\n if res == -1 && errno == EINTR {\n continue\n }\n return res\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Descriptor.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// Source: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/descriptor.go\n\nimport Foundation\n\n/// Descriptor describes the disposition of targeted content.\n/// This structure provides `application/vnd.oci.descriptor.v1+json` mediatype\n/// when marshalled to JSON.\npublic struct Descriptor: Codable, Sendable, Equatable {\n /// mediaType is the media type of the object this schema refers to.\n public let mediaType: String\n\n /// digest is the digest of the targeted content.\n public let digest: String\n\n /// size specifies the size in bytes of the blob.\n public let size: Int64\n\n /// urls specifies a list of URLs from which this object MAY be downloaded.\n public let urls: [String]?\n\n /// annotations contains arbitrary metadata relating to the targeted content.\n public var annotations: [String: String]?\n\n /// platform describes the platform which the image in the manifest runs on.\n ///\n /// This should only be used when referring to a manifest.\n public var platform: Platform?\n\n public init(\n mediaType: String, digest: String, size: Int64, urls: [String]? = nil, annotations: [String: String]? = nil,\n platform: Platform? = nil\n ) {\n self.mediaType = mediaType\n self.digest = digest\n self.size = size\n self.urls = urls\n self.annotations = annotations\n self.platform = platform\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/AddressAllocator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Conforming objects can allocate and free various address types.\npublic protocol AddressAllocator: Sendable {\n associatedtype AddressType: Sendable\n\n /// Allocate a new address.\n func allocate() throws -> AddressType\n\n /// Attempt to reserve a specific address.\n func reserve(_ address: AddressType) throws\n\n /// Free an allocated address.\n func release(_ address: AddressType) throws\n\n /// If no addresses are allocated, prevent future allocations and return true.\n func disableAllocator() -> Bool\n}\n\n/// Errors that a type implementing AddressAllocator should throw.\npublic enum AllocatorError: Swift.Error, CustomStringConvertible, Equatable {\n case allocatorDisabled\n case allocatorFull\n case alreadyAllocated(_ address: String)\n case invalidAddress(_ index: String)\n case invalidArgument(_ msg: String)\n case invalidIndex(_ index: Int)\n case notAllocated(_ address: String)\n case rangeExceeded\n\n public var description: String {\n switch self {\n case .allocatorDisabled:\n return \"the allocator is shutting down\"\n case .allocatorFull:\n return \"no free indices are available for allocation\"\n case .alreadyAllocated(let address):\n return \"cannot choose already-allocated address \\(address)\"\n case .invalidAddress(let address):\n return \"cannot create index using address \\(address)\"\n case .invalidArgument(let msg):\n return \"invalid argument: \\(msg)\"\n case .invalidIndex(let index):\n return \"cannot create address using index \\(index)\"\n case .notAllocated(let address):\n return \"cannot free unallocated address \\(address)\"\n case .rangeExceeded:\n return \"cannot create allocator that overflows maximum address value\"\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/ProgressEvent.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A progress update event.\npublic struct ProgressEvent: Sendable {\n /// The event name. The possible values:\n /// - `add-items`: Increment the number of processed items by `value`.\n /// - `add-total-items`: Increment the total number of items to process by `value`.\n /// - `add-size`: Increment the size of processed items by `value`.\n /// - `add-total-size`: Increment the total size of items to process by `value`.\n public let event: String\n /// The event value.\n public let value: any Sendable\n\n /// Creates an instance.\n /// - Parameters:\n /// - event: The event name.\n /// - value: The event value.\n public init(event: String, value: any Sendable) {\n self.event = event\n self.value = value\n }\n}\n\n/// The progress update handler.\npublic typealias ProgressHandler = @Sendable (_ events: [ProgressEvent]) async -> Void\n"], ["/containerization/Sources/ContainerizationOS/BinaryInteger+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension BinaryInteger {\n private func toUnsignedMemoryAmount(_ amount: UInt64) -> UInt64 {\n guard self > 0 else {\n fatalError(\"encountered negative number during conversion to memory amount\")\n }\n let val = UInt64(self)\n let (newVal, overflow) = val.multipliedReportingOverflow(by: amount)\n guard !overflow else {\n fatalError(\"UInt64 overflow when converting to memory amount\")\n }\n return newVal\n }\n\n public func kib() -> UInt64 {\n self.toUnsignedMemoryAmount(1 << 10)\n }\n\n public func mib() -> UInt64 {\n self.toUnsignedMemoryAmount(1 << 20)\n }\n\n public func gib() -> UInt64 {\n self.toUnsignedMemoryAmount(1 << 30)\n }\n\n public func tib() -> UInt64 {\n self.toUnsignedMemoryAmount(1 << 40)\n }\n\n public func pib() -> UInt64 {\n self.toUnsignedMemoryAmount(1 << 50)\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/Integer+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension UInt64 {\n public var lo: UInt32 {\n UInt32(self & 0xffff_ffff)\n }\n\n public var hi: UInt32 {\n UInt32(self >> 32)\n }\n\n public static func - (lhs: Self, rhs: UInt32) -> UInt64 {\n lhs - UInt64(rhs)\n }\n\n public static func % (lhs: Self, rhs: UInt32) -> UInt64 {\n lhs % UInt64(rhs)\n }\n\n public static func / (lhs: Self, rhs: UInt32) -> UInt32 {\n (lhs / UInt64(rhs)).lo\n }\n\n public static func * (lhs: Self, rhs: UInt32) -> UInt64 {\n lhs * UInt64(rhs)\n }\n\n public static func * (lhs: Self, rhs: Int) -> UInt64 {\n lhs * UInt64(rhs)\n }\n}\n\nextension UInt32 {\n public var lo: UInt16 {\n UInt16(self & 0xffff)\n }\n\n public var hi: UInt16 {\n UInt16(self >> 16)\n }\n\n public static func + (lhs: Self, rhs: Int.IntegerLiteralType) -> UInt32 {\n lhs + UInt32(rhs)\n }\n\n public static func - (lhs: Self, rhs: Int.IntegerLiteralType) -> UInt32 {\n lhs - UInt32(rhs)\n }\n\n public static func / (lhs: Self, rhs: Int.IntegerLiteralType) -> UInt32 {\n lhs / UInt32(rhs)\n }\n\n public static func - (lhs: Self, rhs: UInt16) -> UInt32 {\n lhs - UInt32(rhs)\n }\n\n public static func * (lhs: Self, rhs: Int.IntegerLiteralType) -> Int {\n Int(lhs) * rhs\n }\n}\n\nextension Int {\n public static func + (lhs: Self, rhs: UInt32) -> Int {\n lhs + Int(rhs)\n }\n\n public static func + (lhs: Self, rhs: UInt32) -> UInt32 {\n UInt32(lhs) + rhs\n }\n}\n\nextension UInt16 {\n func isDir() -> Bool {\n self & EXT4.FileModeFlag.TypeMask.rawValue == EXT4.FileModeFlag.S_IFDIR.rawValue\n }\n\n func isLink() -> Bool {\n self & EXT4.FileModeFlag.TypeMask.rawValue == EXT4.FileModeFlag.S_IFLNK.rawValue\n }\n\n func isReg() -> Bool {\n self & EXT4.FileModeFlag.TypeMask.rawValue == EXT4.FileModeFlag.S_IFREG.rawValue\n }\n\n func fileType() -> UInt8 {\n typealias FMode = EXT4.FileModeFlag\n typealias FileType = EXT4.FileType\n switch self & FMode.TypeMask.rawValue {\n case FMode.S_IFREG.rawValue:\n return FileType.regular.rawValue\n case FMode.S_IFDIR.rawValue:\n return FileType.directory.rawValue\n case FMode.S_IFCHR.rawValue:\n return FileType.character.rawValue\n case FMode.S_IFBLK.rawValue:\n return FileType.block.rawValue\n case FMode.S_IFIFO.rawValue:\n return FileType.fifo.rawValue\n case FMode.S_IFSOCK.rawValue:\n return FileType.socket.rawValue\n case FMode.S_IFLNK.rawValue:\n return FileType.symbolicLink.rawValue\n default:\n return FileType.unknown.rawValue\n }\n }\n}\n\nextension [UInt8] {\n var allZeros: Bool {\n for num in self where num != 0 {\n return false\n }\n return true\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Index.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// Source: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/index.go\n\nimport Foundation\n\n/// Index references manifests for various platforms.\n/// This structure provides `application/vnd.oci.image.index.v1+json` mediatype when marshalled to JSON.\npublic struct Index: Codable, Sendable {\n /// schemaVersion is the image manifest schema that this image follows\n public let schemaVersion: Int\n\n /// mediaType specifies the type of this document data structure e.g. `application/vnd.oci.image.index.v1+json`\n public let mediaType: String\n\n /// manifests references platform specific manifests.\n public var manifests: [Descriptor]\n\n /// annotations contains arbitrary metadata for the image index.\n public var annotations: [String: String]?\n\n public init(\n schemaVersion: Int = 2, mediaType: String = MediaTypes.index, manifests: [Descriptor],\n annotations: [String: String]? = nil\n ) {\n self.schemaVersion = schemaVersion\n self.mediaType = mediaType\n self.manifests = manifests\n self.annotations = annotations\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/Content.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport Crypto\nimport Foundation\nimport NIOCore\n\n/// Protocol for defining a single OCI content\npublic protocol Content: Sendable {\n /// URL to the content\n var path: URL { get }\n\n /// sha256 of content\n func digest() throws -> SHA256.Digest\n\n /// Size of content\n func size() throws -> UInt64\n\n /// Data representation of entire content\n func data() throws -> Data\n\n /// Data representation partial content\n func data(offset: UInt64, length: Int) throws -> Data?\n\n /// Decode the content into an object\n func decode() throws -> T where T: Decodable\n}\n\n/// Protocol defining methods to fetch and push OCI content\npublic protocol ContentClient: Sendable {\n func fetch(name: String, descriptor: Descriptor) async throws -> T\n\n func fetchBlob(name: String, descriptor: Descriptor, into file: URL, progress: ProgressHandler?) async throws -> (Int64, SHA256Digest)\n\n func fetchData(name: String, descriptor: Descriptor) async throws -> Data\n\n func push(\n name: String,\n ref: String,\n descriptor: Descriptor,\n streamGenerator: () throws -> T,\n progress: ProgressHandler?\n ) async throws where T.Element == ByteBuffer\n\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/AsyncTypes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npackage actor AsyncStore {\n private var _value: T?\n\n package init(_ value: T? = nil) {\n self._value = value\n }\n\n package func get() -> T? {\n self._value\n }\n\n package func set(_ value: T) {\n self._value = value\n }\n}\n\npackage actor AsyncSet {\n private var buffer: Set\n\n package init(_ elements: S) where S.Element == T {\n buffer = Set(elements)\n }\n\n package var count: Int {\n buffer.count\n }\n\n package func insert(_ element: T) {\n buffer.insert(element)\n }\n\n @discardableResult\n package func remove(_ element: T) -> T? {\n buffer.remove(element)\n }\n\n package func contains(_ element: T) -> Bool {\n buffer.contains(element)\n }\n}\n"], ["/containerization/Sources/Containerization/Image/Unpacker/Unpacker.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\n/// The `Unpacker` protocol defines a standardized interface that involves\n/// decompressing, extracting image layers and preparing it for use.\n///\n/// The `Unpacker` is responsible for managing the lifecycle of the\n/// unpacking process, including any temporary files or resources, until the\n/// `Mount` object is produced.\npublic protocol Unpacker {\n\n /// Unpacks the provided image to a specified path for a given platform.\n ///\n /// This asynchronous method should handle the entire unpacking process, from reading\n /// the `Image` layers for the given `Platform` via its `Manifest`,\n /// to making the extracted contents available as a `Mount`.\n /// Implementations of this method may apply platform-specific optimizations\n /// or transformations during the unpacking.\n ///\n /// Progress updates can be observed via the optional `progress` handler.\n func unpack(_ image: Image, for platform: Platform, at path: URL, progress: ProgressHandler?) async throws -> Mount\n\n}\n"], ["/containerization/Sources/ContainerizationOS/Sysctl.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Helper type to deal with system control functionalities.\npublic struct Sysctl {\n #if os(macOS)\n /// Simple `sysctlbyname` wrapper.\n public static func byName(_ name: String) throws -> Int64 {\n var num: Int64 = 0\n var size = MemoryLayout.size\n if sysctlbyname(name, &num, &size, nil, 0) != 0 {\n throw POSIXError.fromErrno()\n }\n return num\n }\n #endif\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/URL+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension URL {\n /// Returns the unescaped absolutePath of a URL joined by separator.\n public func absolutePath() -> String {\n #if os(macOS)\n return self.path(percentEncoded: false)\n #else\n return self.path\n #endif\n }\n\n /// Returns the domain name of a registry.\n public var domain: String? {\n guard let host = self.absoluteString.split(separator: \":\").first else {\n return nil\n }\n return String(host)\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/String+Extension.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension String {\n /// Removes any prefix (sha256:) from a digest string.\n public var trimmingDigestPrefix: String {\n let split = self.split(separator: \":\")\n if split.count == 2 {\n return String(split[1])\n }\n return self\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/FileTimestamps.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct FileTimestamps {\n public var access: Date\n public var modification: Date\n public var creation: Date\n public var now: Date\n\n public var accessLo: UInt32 {\n access.fs().lo\n }\n\n public var accessHi: UInt32 {\n access.fs().hi\n }\n\n public var modificationLo: UInt32 {\n modification.fs().lo\n }\n\n public var modificationHi: UInt32 {\n modification.fs().hi\n }\n\n public var creationLo: UInt32 {\n creation.fs().lo\n }\n\n public var creationHi: UInt32 {\n creation.fs().hi\n }\n\n public var nowLo: UInt32 {\n now.fs().lo\n }\n\n public var nowHi: UInt32 {\n now.fs().hi\n }\n\n public init(access: Date?, modification: Date?, creation: Date?) {\n now = Date()\n self.access = access ?? now\n self.modification = modification ?? now\n self.creation = creation ?? now\n }\n\n public init() {\n self.init(access: nil, modification: nil, creation: nil)\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/FileManager+Temporary.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension FileManager {\n /// Returns a unique temporary directory to use.\n public func uniqueTemporaryDirectory(create: Bool = true) -> URL {\n let tempDirectoryURL = temporaryDirectory\n let uniqueDirectoryURL = tempDirectoryURL.appendingPathComponent(UUID().uuidString)\n if create {\n try? createDirectory(at: uniqueDirectoryURL, withIntermediateDirectories: true, attributes: nil)\n }\n return uniqueDirectoryURL\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Socket/SocketType.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if canImport(Musl)\nimport Musl\n#elseif canImport(Glibc)\nimport Glibc\n#elseif canImport(Darwin)\nimport Darwin\n#else\n#error(\"SocketType not supported on this platform.\")\n#endif\n\n/// Protocol used to describe the family of socket to be created with `Socket`.\npublic protocol SocketType: Sendable, CustomStringConvertible {\n /// The domain for the socket (AF_UNIX, AF_VSOCK etc.)\n var domain: Int32 { get }\n /// The type of socket (SOCK_STREAM).\n var type: Int32 { get }\n\n /// Actions to perform before calling bind(2).\n func beforeBind(fd: Int32) throws\n /// Actions to perform before calling listen(2).\n func beforeListen(fd: Int32) throws\n\n /// Handle accept(2) for an implementation of a socket type.\n func accept(fd: Int32) throws -> (Int32, SocketType)\n /// Provide a sockaddr pointer (by casting a socket specific type like sockaddr_un for example).\n func withSockAddr(_ closure: (_ ptr: UnsafePointer, _ len: UInt32) throws -> Void) throws\n}\n\nextension SocketType {\n public func beforeBind(fd: Int32) {}\n public func beforeListen(fd: Int32) {}\n}\n"], ["/containerization/Sources/ContainerizationOS/POSIXError+Helpers.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension POSIXError {\n public static func fromErrno() -> POSIXError {\n guard let errCode = POSIXErrorCode(rawValue: errno) else {\n fatalError(\"failed to convert errno to POSIXErrorCode\")\n }\n return POSIXError(errCode)\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/SHA256+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Crypto\nimport Foundation\n\nextension SHA256.Digest {\n /// Returns the digest as a string.\n public var digestString: String {\n let parts = self.description.split(separator: \": \")\n return \"sha256:\\(parts[1])\"\n }\n\n /// Returns the digest without a 'sha256:' prefix.\n public var encoded: String {\n let parts = self.description.split(separator: \": \")\n return String(parts[1])\n }\n}\n"], ["/containerization/Sources/Containerization/Hash.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\n\nimport Crypto\nimport ContainerizationError\n\nfunc hashMountSource(source: String) throws -> String {\n guard let data = source.data(using: .utf8) else {\n throw ContainerizationError(.invalidArgument, message: \"\\(source) could not be converted to Data\")\n }\n return String(SHA256.hash(data: data).encoded.prefix(36))\n}\n\n#endif\n"], ["/containerization/Sources/Containerization/VirtualMachineAgent+Additions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Protocol to conform to if your agent is capable of relaying unix domain socket\n/// connections.\npublic protocol SocketRelayAgent {\n func relaySocket(port: UInt32, configuration: UnixSocketConfiguration) async throws\n func stopSocketRelay(configuration: UnixSocketConfiguration) async throws\n}\n"], ["/containerization/Sources/ContainerizationOCI/Version.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic struct RuntimeSpecVersion: Sendable {\n public let major, minor, patch: Int\n public let dev: String\n\n public static let current = RuntimeSpecVersion(\n major: 1,\n minor: 0,\n patch: 2,\n dev: \"-dev\"\n )\n\n public init(major: Int, minor: Int, patch: Int, dev: String) {\n self.major = major\n self.minor = minor\n self.patch = patch\n self.dev = dev\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/TempDir.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport Foundation\n\ninternal func createTemporaryDirectory(baseName: String) -> URL? {\n let url = FileManager.default.uniqueTemporaryDirectory().appendingPathComponent(\n \"\\(baseName).XXXXXX\")\n guard let templatePathData = (url.absoluteURL.path as NSString).utf8String else {\n return nil\n }\n\n let pathData = UnsafeMutablePointer(mutating: templatePathData)\n mkdtemp(pathData)\n\n return URL(fileURLWithPath: String(cString: pathData), isDirectory: true)\n}\n"], ["/containerization/Sources/Containerization/NATInterface.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic struct NATInterface: Interface {\n public var address: String\n public var gateway: String?\n public var macAddress: String?\n\n public init(address: String, gateway: String?, macAddress: String? = nil) {\n self.address = address\n self.gateway = gateway\n self.macAddress = macAddress\n }\n}\n"], ["/containerization/Sources/Containerization/Container.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// The core protocol container implementations must implement.\npublic protocol Container {\n /// ID for the container.\n var id: String { get }\n /// The amount of cpus assigned to the container.\n var cpus: Int { get }\n /// The memory in bytes assigned to the container.\n var memoryInBytes: UInt64 { get }\n /// The network interfaces assigned to the container.\n var interfaces: [any Interface] { get }\n}\n"], ["/containerization/Sources/Containerization/SystemPlatform.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOCI\n\n/// `SystemPlatform` describes an operating system and architecture pair.\n/// This is primarily used to choose what kind of OCI image to pull from a\n/// registry.\npublic struct SystemPlatform: Sendable, Codable {\n public enum OS: String, CaseIterable, Sendable, Codable {\n case linux\n case darwin\n }\n public let os: OS\n\n public enum Architecture: String, CaseIterable, Sendable, Codable {\n case arm64\n case amd64\n }\n public let architecture: Architecture\n\n public func ociPlatform() -> ContainerizationOCI.Platform {\n ContainerizationOCI.Platform(arch: architecture.rawValue, os: os.rawValue)\n }\n\n public static var linuxArm: SystemPlatform { .init(os: .linux, architecture: .arm64) }\n public static var linuxAmd: SystemPlatform { .init(os: .linux, architecture: .amd64) }\n}\n"], ["/containerization/Sources/SendablePropertyMacros/SendablePropertyError.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Errors that can be thrown by `@SendableProperty`.\nenum SendablePropertyError: CustomStringConvertible, Error {\n case unexpectedError\n case onlyApplicableToVar\n case notApplicableToType\n\n var description: String {\n switch self {\n case .unexpectedError: return \"The macro encountered an unexpected error\"\n case .onlyApplicableToVar: return \"The macro can only be applied to a variable\"\n case .notApplicableToType: return \"The macro can't be applied to a variable of this type\"\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/AnnotationKeys.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// AnnotationKeys contains a subset of \"dictionary keys\" for commonly used annotations in an OCI Image Descriptor\n/// https://github.com/opencontainers/image-spec/blob/main/annotations.md\npublic struct AnnotationKeys: Codable, Sendable {\n public static let containerizationIndexIndirect = \"com.apple.containerization.index.indirect\"\n public static let containerizationImageName = \"com.apple.containerization.image.name\"\n public static let containerdImageName = \"io.containerd.image.name\"\n public static let openContainersImageName = \"org.opencontainers.image.ref.name\"\n}\n"], ["/containerization/vminitd/Sources/vminitd/IOCloser+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\n\nextension Socket: IOCloser {}\n\nextension Terminal: IOCloser {\n var fileDescriptor: Int32 {\n self.handle.fileDescriptor\n }\n}\n\nextension FileHandle: IOCloser {}\n"], ["/containerization/Sources/Containerization/Interface.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A network interface.\npublic protocol Interface: Sendable {\n /// The interface IPv4 address and subnet prefix length, as a CIDR address.\n /// Example: `192.168.64.3/24`\n var address: String { get }\n\n /// The IP address for the default route, or nil for no default route.\n var gateway: String? { get }\n\n /// The interface MAC address, or nil to auto-configure the address.\n var macAddress: String? { get }\n}\n"], ["/containerization/Sources/ContainerizationOCI/MediaType.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// MediaTypes represent all supported OCI image content types for both metadata and layer formats.\n/// Follows all distributable media types in: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/mediatype.go\npublic struct MediaTypes: Codable, Sendable {\n /// Specifies the media type for a content descriptor.\n public static let descriptor = \"application/vnd.oci.descriptor.v1+json\"\n\n /// Specifies the media type for the oci-layout.\n public static let layoutHeader = \"application/vnd.oci.layout.header.v1+json\"\n\n /// Specifies the media type for an image index.\n public static let index = \"application/vnd.oci.image.index.v1+json\"\n\n /// Specifies the media type for an image manifest.\n public static let imageManifest = \"application/vnd.oci.image.manifest.v1+json\"\n\n /// Specifies the media type for the image configuration.\n public static let imageConfig = \"application/vnd.oci.image.config.v1+json\"\n\n /// Specifies the media type for an unused blob containing the value \"{}\".\n public static let emptyJSON = \"application/vnd.oci.empty.v1+json\"\n\n /// Specifies the media type for a Docker image manifest.\n public static let dockerManifest = \"application/vnd.docker.distribution.manifest.v2+json\"\n\n /// Specifies the media type for a Docker image manifest list.\n public static let dockerManifestList = \"application/vnd.docker.distribution.manifest.list.v2+json\"\n\n /// The Docker media type used for image configurations.\n public static let dockerImageConfig = \"application/vnd.docker.container.image.v1+json\"\n\n /// The media type used for layers referenced by the manifest.\n public static let imageLayer = \"application/vnd.oci.image.layer.v1.tar\"\n\n /// The media type used for gzipped layers referenced by the manifest.\n public static let imageLayerGzip = \"application/vnd.oci.image.layer.v1.tar+gzip\"\n\n /// The media type used for zstd compressed layers referenced by the manifest.\n public static let imageLayerZstd = \"application/vnd.oci.image.layer.v1.tar+zstd\"\n\n /// The Docker media type used for uncompressed layers referenced by an image manifest.\n public static let dockerImageLayer = \"application/vnd.docker.image.rootfs.diff.tar\"\n\n /// The Docker media type used for gzipped layers referenced by an image manifest.\n public static let dockerImageLayerGzip = \"application/vnd.docker.image.rootfs.diff.tar.gzip\"\n\n /// The Docker media type used for zstd compressed layers referenced by an image manifest.\n public static let dockerImageLayerZstd = \"application/vnd.docker.image.rootfs.diff.tar.zstd\"\n\n /// The media type used for in-toto attestations blobs.\n public static let inTotoAttestationBlob = \"application/vnd.in-toto+json\"\n}\n"], ["/containerization/Sources/Containerization/IO/ReaderStream.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A type that returns a stream of Data.\npublic protocol ReaderStream: Sendable {\n func stream() -> AsyncStream\n}\n"], ["/containerization/vminitd/Sources/vminitd/IOCloser.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nprotocol IOCloser: Sendable {\n var fileDescriptor: Int32 { get }\n\n func close() throws\n}\n"], ["/containerization/Sources/Containerization/VirtualMachineManager.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A protocol to implement for virtual machine isolated containers.\npublic protocol VirtualMachineManager: Sendable {\n func create(container: Container) throws -> any VirtualMachineInstance\n}\n"], ["/containerization/Sources/SendablePropertyMacros/SendablePropertyPlugin.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport SwiftCompilerPlugin\nimport SwiftSyntaxMacros\n\n/// A plugin that registers the `SendablePropertyMacroUnchecked` and `SendablePropertyMacro`.\n@main\nstruct SendablePropertyPlugin: CompilerPlugin {\n let providingMacros: [Macro.Type] = [\n SendablePropertyMacroUnchecked.self,\n SendablePropertyMacro.self,\n ]\n}\n"], ["/containerization/Sources/Containerization/IO/Writer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A type that writes the provided Data.\npublic protocol Writer: Sendable {\n func write(_ data: Data) throws\n}\n"], ["/containerization/Sources/SendableProperty/SendableProperty.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// A declaration of the `@SendableProperty` macro.\n@attached(peer, names: arbitrary)\n@attached(accessor)\npublic macro SendableProperty() = #externalMacro(module: \"SendablePropertyMacros\", type: \"SendablePropertyMacro\")\n"], ["/containerization/Sources/SendableProperty/SendablePropertyUnchecked.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// A declaration of the `@SendablePropertyUnchecked` macro.\n@attached(peer, names: arbitrary)\n@attached(accessor)\npublic macro SendablePropertyUnchecked() = #externalMacro(module: \"SendablePropertyMacros\", type: \"SendablePropertyMacroUnchecked\")\n"]], "task_instance_info": {"created_time": "2025-08-21 03:23:08", "created_task_model": "DeepSeek-R1", "function_skeleton": "public func delete ( ) async throws { }", "code_description": "This code segment functions to: Terminate and release all allocated resources associated with the managed process, including remote process deletion, input/output stream closure, and agent connection termination while handling error conditions through logging and exception propagation."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```swift\n[TASK_BEGIN]\n public func delete() async throws {\n do {\n try await agent.deleteProcess(\n id: self.id,\n containerID: self.owningContainer\n )\n try self.state.withLock { state in\n try state.stdio.close()\n state.stdinRelay?.cancel()\n state.stdinRelay = nil\n state.pid = -1\n state.ioTracker = nil\n }\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to delete process\",\n cause: error\n )\n }\n }\n[TASK_END]\n```", "inference_time": "2025-08-21 03-23-35"}, "editdistance_info": {"edit_distance": 43.3862, "calculate_time": "2025-08-21 03:23:35", "true_code_clean": "public func delete() async throws {\n do {\n try await self.agent.deleteProcess(\n id: self.id,\n containerID: self.owningContainer\n )\n } catch {\n self.logger?.error(\n \"process deletion\",\n metadata: [\n \"id\": \"\\(self.id)\",\n \"error\": \"\\(error)\",\n ])\n }\n do {\n try self.state.withLock {\n $0.stdinRelay?.cancel()\n try $0.stdio.close()\n }\n } catch {\n self.logger?.error(\n \"closing process stdio\",\n metadata: [\n \"id\": \"\\(self.id)\",\n \"error\": \"\\(error)\",\n ])\n }\n do {\n try await self.agent.close()\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to close agent connection\",\n cause: error,\n )\n }\n }", "predict_code_clean": "public func delete() async throws {\n do {\n try await agent.deleteProcess(\n id: self.id,\n containerID: self.owningContainer\n )\n try self.state.withLock { state in\n try state.stdio.close()\n state.stdinRelay?.cancel()\n state.stdinRelay = nil\n state.pid = -1\n state.ioTracker = nil\n }\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to delete process\",\n cause: error\n )\n }\n }"}} +{"repo_name": "containerization", "file_name": "/containerization/vminitd/Sources/vminitd/VsockProxy.swift", "inference_info": {"prefix_code": "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationIO\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport SendableProperty\n\nfinal class VsockProxy: Sendable {\n enum Action {\n case listen\n case dial\n }\n\n private enum SocketType {\n case unix\n case vsock\n }\n\n init(\n id: String,\n action: Action,\n port: UInt32,\n path: URL,\n udsPerms: UInt32?,\n log: Logger? = nil\n ) {\n self.id = id\n self.action = action\n self.port = port\n self.path = path\n self.udsPerms = udsPerms\n self.log = log\n }\n\n public let id: String\n private let path: URL\n private let action: Action\n private let port: UInt32\n private let udsPerms: UInt32?\n private let log: Logger?\n\n @SendableProperty\n private var listener: Socket?\n private let task = Mutex?>(nil)\n}\n\nextension VsockProxy {\n func close() throws {\n guard let listener else {\n return\n }\n\n try listener.close()\n let fm = FileManager.default\n if fm.fileExists(atPath: self.path.path) {\n try FileManager.default.removeItem(at: self.path)\n }\n let task = task.withLock { $0 }\n task?.cancel()\n }\n\n func start() throws {\n switch self.action {\n case .dial:\n try dialHost()\n case .listen:\n try dialGuest()\n }\n }\n\n private func dialHost() throws {\n let fm = FileManager.default\n\n let parentDir = self.path.deletingLastPathComponent()\n try fm.createDirectory(\n at: parentDir,\n withIntermediateDirectories: true\n )\n\n let type = try UnixType(\n path: self.path.path,\n perms: self.udsPerms,\n unlinkExisting: true\n )\n let uds = try Socket(type: type)\n try uds.listen()\n listener = uds\n\n try self.acceptLoop(socketType: .unix)\n }\n\n private func dialGuest() throws {\n let type = VsockType(\n port: self.port,\n cid: VsockType.anyCID\n )\n let vsock = try Socket(type: type)\n try vsock.listen()\n listener = vsock\n\n try self.acceptLoop(socketType: .vsock)\n }\n\n private func acceptLoop(socketType: SocketType) throws {\n guard let listener else {\n return\n }\n\n let stream = try listener.acceptStream()\n let task = Task {\n do {\n for try await conn in stream {\n Task {\n do {\n try await handleConn(\n conn: conn,\n connType: socketType\n )\n } catch {\n self.log?.error(\"failed to handle connection: \\(error)\")\n }\n }\n }\n } catch {\n self.log?.error(\"failed to accept connection: \\(error)\")\n }\n }\n self.task.withLock { $0 = task }\n }\n\n ", "suffix_code": "\n}\n", "middle_code": "private func handleConn(\n conn: ContainerizationOS.Socket,\n connType: SocketType\n ) async throws {\n try await withCheckedThrowingContinuation { (c: CheckedContinuation) in\n do {\n nonisolated(unsafe) var relayTo: ContainerizationOS.Socket\n switch connType {\n case .unix:\n let type = VsockType(\n port: self.port,\n cid: VsockType.hostCID\n )\n relayTo = try Socket(\n type: type,\n closeOnDeinit: false\n )\n case .vsock:\n let type = try UnixType(path: self.path.path)\n relayTo = try Socket(\n type: type,\n closeOnDeinit: false\n )\n }\n try relayTo.connect()\n nonisolated(unsafe) var clientFile = OSFile.SpliceFile(fd: conn.fileDescriptor)\n nonisolated(unsafe) var serverFile = OSFile.SpliceFile(fd: relayTo.fileDescriptor)\n let cleanup = { @Sendable in\n do {\n try ProcessSupervisor.default.poller.delete(clientFile.fileDescriptor)\n try ProcessSupervisor.default.poller.delete(serverFile.fileDescriptor)\n try conn.close()\n try relayTo.close()\n } catch {\n self.log?.error(\"Failed to clean up vsock proxy: \\(error)\")\n }\n c.resume()\n }\n try! ProcessSupervisor.default.poller.add(clientFile.fileDescriptor, mask: EPOLLIN | EPOLLOUT) { mask in\n if mask.readyToRead {\n do {\n let (_, _, action) = try OSFile.splice(from: &clientFile, to: &serverFile)\n if action == .eof || action == .brokenPipe {\n return cleanup()\n }\n } catch {\n return cleanup()\n }\n }\n if mask.readyToWrite {\n do {\n let (_, _, action) = try OSFile.splice(from: &serverFile, to: &clientFile)\n if action == .eof || action == .brokenPipe {\n return cleanup()\n }\n } catch {\n return cleanup()\n }\n }\n if mask.isHangup {\n return cleanup()\n }\n }\n try! ProcessSupervisor.default.poller.add(serverFile.fileDescriptor, mask: EPOLLIN | EPOLLOUT) { mask in\n if mask.readyToRead {\n do {\n let (_, _, action) = try OSFile.splice(from: &serverFile, to: &clientFile)\n if action == .eof || action == .brokenPipe {\n return cleanup()\n }\n } catch {\n return cleanup()\n }\n }\n if mask.readyToWrite {\n do {\n let (_, _, action) = try OSFile.splice(from: &clientFile, to: &serverFile)\n if action == .eof || action == .brokenPipe {\n return cleanup()\n }\n } catch {\n return cleanup()\n }\n }\n if mask.isHangup {\n return cleanup()\n }\n }\n } catch {\n c.resume(throwing: error)\n }\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "swift", "sub_task_type": null}, "context_code": [["/containerization/Sources/Containerization/UnixSocketRelay.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationIO\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport Synchronization\n\npackage actor UnixSocketRelayManager {\n private let vm: any VirtualMachineInstance\n private var relays: [String: SocketRelay]\n private let q: DispatchQueue\n private let log: Logger?\n\n init(vm: any VirtualMachineInstance, log: Logger? = nil) {\n self.vm = vm\n self.relays = [:]\n self.q = DispatchQueue(label: \"com.apple.containerization.socket-relay\")\n self.log = log\n }\n}\n\nextension UnixSocketRelayManager {\n func start(port: UInt32, socket: UnixSocketConfiguration) async throws {\n guard self.relays[socket.id] == nil else {\n throw ContainerizationError(\n .invalidState,\n message: \"socket relay \\(socket.id) already started\"\n )\n }\n\n let socketRelay = try SocketRelay(\n port: port,\n socket: socket,\n vm: self.vm,\n queue: self.q,\n log: self.log\n )\n\n do {\n self.relays[socket.id] = socketRelay\n try await socketRelay.start()\n } catch {\n self.relays.removeValue(forKey: socket.id)\n }\n }\n\n func stop(socket: UnixSocketConfiguration) async throws {\n guard let storedRelay = self.relays.removeValue(forKey: socket.id) else {\n throw ContainerizationError(\n .notFound,\n message: \"failed to stop socket relay\"\n )\n }\n try storedRelay.stop()\n }\n\n func stopAll() async throws {\n for (_, relay) in self.relays {\n try relay.stop()\n }\n }\n}\n\npackage final class SocketRelay: Sendable {\n private let port: UInt32\n private let configuration: UnixSocketConfiguration\n private let log: Logger?\n private let vm: any VirtualMachineInstance\n private let q: DispatchQueue\n private let state: Mutex\n\n private struct State {\n var relaySources: [String: ConnectionSources] = [:]\n var t: Task<(), Never>? = nil\n }\n\n // `DispatchSourceRead` is thread-safe.\n private struct ConnectionSources: @unchecked Sendable {\n let hostSource: DispatchSourceRead\n let guestSource: DispatchSourceRead\n }\n\n init(\n port: UInt32,\n socket: UnixSocketConfiguration,\n vm: any VirtualMachineInstance,\n queue: DispatchQueue,\n log: Logger? = nil\n ) throws {\n self.port = port\n self.configuration = socket\n self.state = Mutex(.init())\n self.vm = vm\n self.log = log\n self.q = queue\n }\n\n deinit {\n self.state.withLock { $0.t?.cancel() }\n }\n}\n\nextension SocketRelay {\n func start() async throws {\n switch configuration.direction {\n case .outOf:\n try await setupHostVsockDial()\n case .into:\n try setupHostVsockListener()\n }\n }\n\n func stop() throws {\n try self.state.withLock {\n guard let t = $0.t else {\n throw ContainerizationError(\n .invalidState,\n message: \"failed to stop socket relay: relay has not been started\"\n )\n }\n t.cancel()\n $0.t = nil\n $0.relaySources.removeAll()\n }\n\n switch configuration.direction {\n case .outOf:\n // If we created the host conn, lets unlink it also. It's possible it was\n // already unlinked if the relay failed earlier.\n try? FileManager.default.removeItem(at: self.configuration.destination)\n case .into:\n try self.vm.stopListen(self.port)\n }\n }\n\n private func setupHostVsockDial() async throws {\n let hostConn = self.configuration.destination\n\n let socketType = try UnixType(\n path: hostConn.path,\n unlinkExisting: true\n )\n let hostSocket = try Socket(type: socketType)\n try hostSocket.listen()\n\n let connectionStream = try hostSocket.acceptStream(closeOnDeinit: false)\n self.state.withLock {\n $0.t = Task {\n do {\n for try await connection in connectionStream {\n try await self.handleHostUnixConn(\n hostConn: connection,\n port: self.port,\n vm: self.vm,\n log: self.log\n )\n }\n } catch {\n log?.error(\"failed in unix socket relay loop: \\(error)\")\n }\n try? FileManager.default.removeItem(at: hostConn)\n }\n }\n }\n\n private func setupHostVsockListener() throws {\n let hostPath = self.configuration.source\n let port = self.port\n let log = self.log\n\n let connectionStream = try self.vm.listen(self.port)\n self.state.withLock {\n $0.t = Task {\n do {\n defer { connectionStream.finish() }\n for await connection in connectionStream.connections {\n try await self.handleGuestVsockConn(\n vsockConn: connection,\n hostConnectionPath: hostPath,\n port: port,\n log: log\n )\n }\n } catch {\n log?.error(\"failed to setup relay between vsock \\(port) and \\(hostPath.path): \\(error)\")\n }\n }\n }\n }\n\n private func handleHostUnixConn(\n hostConn: ContainerizationOS.Socket,\n port: UInt32,\n vm: any VirtualMachineInstance,\n log: Logger?\n ) async throws {\n do {\n let guestConn = try await vm.dial(port)\n try await self.relay(\n hostConn: hostConn,\n guestFd: guestConn.fileDescriptor\n )\n } catch {\n log?.error(\"failed to relay between vsock \\(port) and \\(hostConn)\")\n throw error\n }\n }\n\n private func handleGuestVsockConn(\n vsockConn: FileHandle,\n hostConnectionPath: URL,\n port: UInt32,\n log: Logger?\n ) async throws {\n let hostPath = hostConnectionPath.path\n let socketType = try UnixType(path: hostPath)\n let hostSocket = try Socket(\n type: socketType,\n closeOnDeinit: false\n )\n try hostSocket.connect()\n\n do {\n try await self.relay(\n hostConn: hostSocket,\n guestFd: vsockConn.fileDescriptor\n )\n } catch {\n log?.error(\"failed to relay between vsock \\(port) and \\(hostPath)\")\n }\n }\n\n private func relay(\n hostConn: Socket,\n guestFd: Int32\n ) async throws {\n let connSource = DispatchSource.makeReadSource(\n fileDescriptor: hostConn.fileDescriptor,\n queue: self.q\n )\n let vsockConnectionSource = DispatchSource.makeReadSource(\n fileDescriptor: guestFd,\n queue: self.q\n )\n\n let pairID = UUID().uuidString\n self.state.withLock {\n $0.relaySources[pairID] = ConnectionSources(\n hostSource: connSource,\n guestSource: vsockConnectionSource\n )\n }\n\n nonisolated(unsafe) let buf1 = UnsafeMutableBufferPointer.allocate(capacity: Int(getpagesize()))\n connSource.setEventHandler {\n Self.fdCopyHandler(\n buffer: buf1,\n source: connSource,\n from: hostConn.fileDescriptor,\n to: guestFd\n )\n }\n\n nonisolated(unsafe) let buf2 = UnsafeMutableBufferPointer.allocate(capacity: Int(getpagesize()))\n vsockConnectionSource.setEventHandler {\n Self.fdCopyHandler(\n buffer: buf2,\n source: vsockConnectionSource,\n from: guestFd,\n to: hostConn.fileDescriptor\n )\n }\n\n connSource.setCancelHandler {\n if !connSource.isCancelled {\n connSource.cancel()\n }\n if !vsockConnectionSource.isCancelled {\n vsockConnectionSource.cancel()\n }\n try? hostConn.close()\n }\n\n vsockConnectionSource.setCancelHandler {\n if !vsockConnectionSource.isCancelled {\n vsockConnectionSource.cancel()\n }\n if !connSource.isCancelled {\n connSource.cancel()\n }\n close(guestFd)\n }\n\n connSource.activate()\n vsockConnectionSource.activate()\n }\n\n private static func fdCopyHandler(\n buffer: UnsafeMutableBufferPointer,\n source: DispatchSourceRead,\n from sourceFd: Int32,\n to destinationFd: Int32,\n log: Logger? = nil\n ) {\n if source.data == 0 {\n if !source.isCancelled {\n source.cancel()\n }\n return\n }\n\n do {\n try self.fileDescriptorCopy(\n buffer: buffer,\n size: source.data,\n from: sourceFd,\n to: destinationFd\n )\n } catch {\n log?.error(\"file descriptor copy failed \\(error)\")\n if !source.isCancelled {\n source.cancel()\n }\n }\n }\n\n private static func fileDescriptorCopy(\n buffer: UnsafeMutableBufferPointer,\n size: UInt,\n from sourceFd: Int32,\n to destinationFd: Int32\n ) throws {\n let bufferSize = buffer.count\n var readBytesRemaining = min(Int(size), bufferSize)\n\n guard let baseAddr = buffer.baseAddress else {\n throw ContainerizationError(\n .invalidState,\n message: \"buffer has no base address\"\n )\n }\n\n while readBytesRemaining > 0 {\n let readResult = read(sourceFd, baseAddr, min(bufferSize, readBytesRemaining))\n if readResult <= 0 {\n throw ContainerizationError(\n .internalError,\n message: \"missing pointer base address\"\n )\n }\n readBytesRemaining -= readResult\n\n var writeBytesRemaining = readResult\n while writeBytesRemaining > 0 {\n let writeResult = write(destinationFd, baseAddr, writeBytesRemaining)\n if writeResult <= 0 {\n throw ContainerizationError(\n .internalError,\n message: \"zero byte write or error in socket relay\"\n )\n }\n writeBytesRemaining -= writeResult\n }\n }\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/IOPair.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport Synchronization\n\nfinal class IOPair: Sendable {\n let readFrom: IOCloser\n let writeTo: IOCloser\n nonisolated(unsafe) let buffer: UnsafeMutableBufferPointer\n private let logger: Logger?\n\n private let done: Atomic\n\n init(readFrom: IOCloser, writeTo: IOCloser, logger: Logger? = nil) {\n self.readFrom = readFrom\n self.writeTo = writeTo\n self.done = Atomic(false)\n self.buffer = UnsafeMutableBufferPointer.allocate(capacity: Int(getpagesize()))\n self.logger = logger\n }\n\n func relay() throws {\n let readFromFd = self.readFrom.fileDescriptor\n let writeToFd = self.writeTo.fileDescriptor\n\n let readFrom = OSFile(fd: readFromFd)\n let writeTo = OSFile(fd: writeToFd)\n\n try ProcessSupervisor.default.poller.add(readFromFd, mask: EPOLLIN) { mask in\n if mask.isHangup && !mask.readyToRead {\n self.close()\n return\n }\n // Loop so that in the case that someone wrote > buf.count down the pipe\n // we properly will drain it fully.\n while true {\n let r = readFrom.read(self.buffer)\n if r.read > 0 {\n let view = UnsafeMutableBufferPointer(\n start: self.buffer.baseAddress,\n count: r.read\n )\n\n let w = writeTo.write(view)\n if w.wrote != r.read {\n self.logger?.error(\"stopping relay: short write for stdio\")\n self.close()\n return\n }\n }\n\n switch r.action {\n case .error(let errno):\n self.logger?.error(\"failed with errno \\(errno) while reading for fd \\(readFromFd)\")\n fallthrough\n case .eof:\n self.close()\n self.logger?.debug(\"closing relay for \\(readFromFd)\")\n return\n case .again:\n // We read all we could, exit.\n if mask.isHangup {\n self.close()\n }\n return\n default:\n break\n }\n }\n }\n }\n\n func close() {\n guard\n self.done.compareExchange(\n expected: false,\n desired: true,\n successOrdering: .acquiringAndReleasing,\n failureOrdering: .acquiring\n ).exchanged\n else {\n return\n }\n\n self.buffer.deallocate()\n\n let readFromFd = self.readFrom.fileDescriptor\n // Remove the fd from our global epoll instance first.\n do {\n try ProcessSupervisor.default.poller.delete(readFromFd)\n } catch {\n self.logger?.error(\"failed to delete fd from epoll \\(readFromFd): \\(error)\")\n }\n\n do {\n try self.readFrom.close()\n } catch {\n self.logger?.error(\"failed to close reader fd for IOPair: \\(error)\")\n }\n\n do {\n try self.writeTo.close()\n } catch {\n self.logger?.error(\"failed to close writer fd for IOPair: \\(error)\")\n }\n }\n}\n"], ["/containerization/Sources/Containerization/LinuxProcess.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport Synchronization\n\n/// `LinuxProcess` represents a Linux process and is used to\n/// setup and control the full lifecycle for the process.\npublic final class LinuxProcess: Sendable {\n /// The ID of the process. This is purely metadata for the caller.\n public let id: String\n\n /// What container owns this process (if any).\n public let owningContainer: String?\n\n package struct StdioSetup: Sendable {\n let port: UInt32\n let writer: Writer\n }\n\n package struct StdioReaderSetup {\n let port: UInt32\n let reader: ReaderStream\n }\n\n package struct Stdio: Sendable {\n let stdin: StdioReaderSetup?\n let stdout: StdioSetup?\n let stderr: StdioSetup?\n }\n\n private struct StdioHandles: Sendable {\n var stdin: FileHandle?\n var stdout: FileHandle?\n var stderr: FileHandle?\n\n mutating func close() throws {\n if let stdin {\n try stdin.close()\n stdin.readabilityHandler = nil\n self.stdin = nil\n }\n if let stdout {\n try stdout.close()\n stdout.readabilityHandler = nil\n self.stdout = nil\n }\n if let stderr {\n try stderr.close()\n stderr.readabilityHandler = nil\n self.stderr = nil\n }\n }\n }\n\n private struct State {\n var spec: ContainerizationOCI.Spec\n var pid: Int32\n var stdio: StdioHandles\n var stdinRelay: Task<(), Never>?\n var ioTracker: IoTracker?\n\n struct IoTracker {\n let stream: AsyncStream\n let cont: AsyncStream.Continuation\n let configuredStreams: Int\n }\n }\n\n /// The process ID for the container process. This will be -1\n /// if the process has not been started.\n public var pid: Int32 {\n state.withLock { $0.pid }\n }\n\n private let state: Mutex\n private let ioSetup: Stdio\n private let agent: any VirtualMachineAgent\n private let vm: any VirtualMachineInstance\n private let logger: Logger?\n\n init(\n _ id: String,\n containerID: String? = nil,\n spec: Spec,\n io: Stdio,\n agent: any VirtualMachineAgent,\n vm: any VirtualMachineInstance,\n logger: Logger?\n ) {\n self.id = id\n self.owningContainer = containerID\n self.state = Mutex(.init(spec: spec, pid: -1, stdio: StdioHandles()))\n self.ioSetup = io\n self.agent = agent\n self.vm = vm\n self.logger = logger\n }\n}\n\nextension LinuxProcess {\n func setupIO(streams: [VsockConnectionStream?]) async throws -> [FileHandle?] {\n let handles = try await Timeout.run(seconds: 3) {\n await withTaskGroup(of: (Int, FileHandle?).self) { group in\n var results = [FileHandle?](repeating: nil, count: 3)\n\n for (index, stream) in streams.enumerated() {\n guard let stream = stream else { continue }\n\n group.addTask {\n let first = await stream.connections.first(where: { _ in true })\n return (index, first)\n }\n }\n\n for await (index, fileHandle) in group {\n results[index] = fileHandle\n }\n return results\n }\n }\n\n if let stdin = self.ioSetup.stdin {\n if let handle = handles[0] {\n self.state.withLock {\n $0.stdinRelay = Task {\n for await data in stdin.reader.stream() {\n do {\n try handle.write(contentsOf: data)\n } catch {\n self.logger?.error(\"failed to write to stdin: \\(error)\")\n break\n }\n }\n\n do {\n self.logger?.debug(\"stdin relay finished, closing\")\n\n // There's two ways we can wind up here:\n //\n // 1. The stream finished on its own (e.g. we wrote all the\n // data) and we will close the underlying stdin in the guest below.\n //\n // 2. The client explicitly called closeStdin() themselves\n // which will cancel this relay task AFTER actually closing\n // the fds. If the client did that, then this task will be\n // cancelled, and the fds are already gone so there's nothing\n // for us to do.\n if Task.isCancelled {\n return\n }\n\n try await self._closeStdin()\n } catch {\n self.logger?.error(\"failed to close stdin: \\(error)\")\n }\n }\n }\n }\n }\n\n var configuredStreams = 0\n let (stream, cc) = AsyncStream.makeStream()\n if let stdout = self.ioSetup.stdout {\n configuredStreams += 1\n handles[1]?.readabilityHandler = { handle in\n do {\n let data = handle.availableData\n if data.isEmpty {\n // This block is called when the producer (the guest) closes\n // the fd it is writing into.\n handles[1]?.readabilityHandler = nil\n cc.yield()\n return\n }\n try stdout.writer.write(data)\n } catch {\n self.logger?.error(\"failed to write to stdout: \\(error)\")\n }\n }\n }\n\n if let stderr = self.ioSetup.stderr {\n configuredStreams += 1\n handles[2]?.readabilityHandler = { handle in\n do {\n let data = handle.availableData\n if data.isEmpty {\n handles[2]?.readabilityHandler = nil\n cc.yield()\n return\n }\n try stderr.writer.write(data)\n } catch {\n self.logger?.error(\"failed to write to stderr: \\(error)\")\n }\n }\n }\n if configuredStreams > 0 {\n self.state.withLock {\n $0.ioTracker = .init(stream: stream, cont: cc, configuredStreams: configuredStreams)\n }\n }\n\n return handles\n }\n\n /// Start the process.\n public func start() async throws {\n do {\n let spec = self.state.withLock { $0.spec }\n var streams = [VsockConnectionStream?](repeating: nil, count: 3)\n if let stdin = self.ioSetup.stdin {\n streams[0] = try self.vm.listen(stdin.port)\n }\n if let stdout = self.ioSetup.stdout {\n streams[1] = try self.vm.listen(stdout.port)\n }\n if let stderr = self.ioSetup.stderr {\n if spec.process!.terminal {\n throw ContainerizationError(\n .invalidArgument,\n message: \"stderr should not be configured with terminal=true\"\n )\n }\n streams[2] = try self.vm.listen(stderr.port)\n }\n\n let t = Task {\n try await self.setupIO(streams: streams)\n }\n\n try await agent.createProcess(\n id: self.id,\n containerID: self.owningContainer,\n stdinPort: self.ioSetup.stdin?.port,\n stdoutPort: self.ioSetup.stdout?.port,\n stderrPort: self.ioSetup.stderr?.port,\n configuration: spec,\n options: nil\n )\n\n let result = try await t.value\n let pid = try await self.agent.startProcess(\n id: self.id,\n containerID: self.owningContainer\n )\n\n self.state.withLock {\n $0.stdio = StdioHandles(\n stdin: result[0],\n stdout: result[1],\n stderr: result[2]\n )\n $0.pid = pid\n }\n } catch {\n if let err = error as? ContainerizationError {\n throw err\n }\n throw ContainerizationError(\n .internalError,\n message: \"failed to start process\",\n cause: error,\n )\n }\n }\n\n /// Kill the process with the specified signal.\n public func kill(_ signal: Int32) async throws {\n do {\n try await agent.signalProcess(\n id: self.id,\n containerID: self.owningContainer,\n signal: signal\n )\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to kill process\",\n cause: error\n )\n }\n }\n\n /// Resize the processes pty (if requested).\n public func resize(to: Terminal.Size) async throws {\n do {\n try await agent.resizeProcess(\n id: self.id,\n containerID: self.owningContainer,\n columns: UInt32(to.width),\n rows: UInt32(to.height)\n )\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to resize process\",\n cause: error\n )\n }\n }\n\n public func closeStdin() async throws {\n do {\n try await self._closeStdin()\n self.state.withLock {\n $0.stdinRelay?.cancel()\n }\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to close stdin\",\n cause: error,\n )\n }\n }\n\n func _closeStdin() async throws {\n try await self.agent.closeProcessStdin(\n id: self.id,\n containerID: self.owningContainer\n )\n }\n\n /// Wait on the process to exit with an optional timeout. Returns the exit code of the process.\n @discardableResult\n public func wait(timeoutInSeconds: Int64? = nil) async throws -> Int32 {\n do {\n let code = try await self.agent.waitProcess(\n id: self.id,\n containerID: self.owningContainer,\n timeoutInSeconds: timeoutInSeconds\n )\n await self.waitIoComplete()\n return code\n } catch {\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(\n .internalError,\n message: \"failed to wait on process\",\n cause: error\n )\n }\n }\n\n /// Wait until the standard output and standard error streams for the process have concluded.\n private func waitIoComplete() async {\n let ioTracker = self.state.withLock { $0.ioTracker }\n guard let ioTracker else {\n return\n }\n do {\n try await Timeout.run(seconds: 3) {\n var counter = ioTracker.configuredStreams\n for await _ in ioTracker.stream {\n counter -= 1\n if counter == 0 {\n ioTracker.cont.finish()\n break\n }\n }\n }\n } catch {\n self.logger?.error(\"Timeout waiting for IO to complete for process \\(id): \\(error)\")\n }\n self.state.withLock {\n $0.ioTracker = nil\n }\n }\n\n /// Cleans up guest state and waits on and closes any host resources (stdio handles).\n public func delete() async throws {\n do {\n try await self.agent.deleteProcess(\n id: self.id,\n containerID: self.owningContainer\n )\n } catch {\n self.logger?.error(\n \"process deletion\",\n metadata: [\n \"id\": \"\\(self.id)\",\n \"error\": \"\\(error)\",\n ])\n }\n\n do {\n try self.state.withLock {\n $0.stdinRelay?.cancel()\n try $0.stdio.close()\n }\n } catch {\n self.logger?.error(\n \"closing process stdio\",\n metadata: [\n \"id\": \"\\(self.id)\",\n \"error\": \"\\(error)\",\n ])\n }\n\n do {\n try await self.agent.close()\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to close agent connection\",\n cause: error,\n )\n }\n }\n}\n"], ["/containerization/Sources/Containerization/VZVirtualMachine+Helpers.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport Logging\nimport Virtualization\nimport ContainerizationError\n\nextension VZVirtualMachine {\n nonisolated func connect(queue: DispatchQueue, port: UInt32) async throws -> VZVirtioSocketConnection {\n try await withCheckedThrowingContinuation { cont in\n queue.sync {\n guard let vsock = self.socketDevices[0] as? VZVirtioSocketDevice else {\n let error = ContainerizationError(.invalidArgument, message: \"no vsock device\")\n cont.resume(throwing: error)\n return\n }\n vsock.connect(toPort: port) { result in\n switch result {\n case .success(let conn):\n // `conn` isn't used concurrently.\n nonisolated(unsafe) let conn = conn\n cont.resume(returning: conn)\n case .failure(let error):\n cont.resume(throwing: error)\n }\n }\n }\n }\n }\n\n func listen(queue: DispatchQueue, port: UInt32, listener: VZVirtioSocketListener) throws {\n try queue.sync {\n guard let vsock = self.socketDevices[0] as? VZVirtioSocketDevice else {\n throw ContainerizationError(.invalidArgument, message: \"no vsock device\")\n }\n vsock.setSocketListener(listener, forPort: port)\n }\n }\n\n func removeListener(queue: DispatchQueue, port: UInt32) throws {\n try queue.sync {\n guard let vsock = self.socketDevices[0] as? VZVirtioSocketDevice else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"no vsock device to remove\"\n )\n }\n vsock.removeSocketListener(forPort: port)\n }\n }\n\n func start(queue: DispatchQueue) async throws {\n try await withCheckedThrowingContinuation { (cont: CheckedContinuation) in\n queue.sync {\n self.start { result in\n if case .failure(let error) = result {\n cont.resume(throwing: error)\n return\n }\n cont.resume()\n }\n }\n }\n }\n\n func stop(queue: DispatchQueue) async throws {\n try await withCheckedThrowingContinuation { (cont: CheckedContinuation) in\n queue.sync {\n self.stop { error in\n if let error {\n cont.resume(throwing: error)\n return\n }\n cont.resume()\n }\n }\n }\n }\n}\n\nextension VZVirtualMachine {\n func waitForAgent(queue: DispatchQueue) async throws -> FileHandle {\n let agentConnectionRetryCount: Int = 150\n let agentConnectionSleepDuration: Duration = .milliseconds(20)\n\n for _ in 0...agentConnectionRetryCount {\n do {\n return try await self.connect(queue: queue, port: Vminitd.port).dupHandle()\n } catch {\n try await Task.sleep(for: agentConnectionSleepDuration)\n continue\n }\n }\n throw ContainerizationError(.invalidArgument, message: \"no connection to agent socket\")\n }\n}\n\nextension VZVirtioSocketConnection {\n func dupHandle() -> FileHandle {\n let fd = dup(self.fileDescriptor)\n self.close()\n return FileHandle(fileDescriptor: fd, closeOnDealloc: false)\n }\n}\n\n#endif\n"], ["/containerization/Sources/Containerization/VZVirtualMachineInstance.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Logging\nimport NIOCore\nimport NIOPosix\nimport Synchronization\nimport Virtualization\n\nstruct VZVirtualMachineInstance: VirtualMachineInstance, Sendable {\n typealias Agent = Vminitd\n\n /// Attached mounts on the sandbox.\n public let mounts: [AttachedFilesystem]\n\n /// Returns the runtime state of the vm.\n public var state: VirtualMachineInstanceState {\n vzStateToInstanceState()\n }\n\n /// The sandbox configuration.\n private let config: Configuration\n public struct Configuration: Sendable {\n /// Amount of cpus to allocated.\n public var cpus: Int\n /// Amount of memory in bytes allocated.\n public var memoryInBytes: UInt64\n /// Toggle rosetta's x86_64 emulation support.\n public var rosetta: Bool\n /// Toggle nested virtualization support.\n public var nestedVirtualization: Bool\n /// Mount attachments.\n public var mounts: [Mount]\n /// Network interface attachments.\n public var interfaces: [any Interface]\n /// Kernel image.\n public var kernel: Kernel?\n /// The root filesystem.\n public var initialFilesystem: Mount?\n /// File path to store the sandbox boot logs.\n public var bootlog: URL?\n\n init() {\n self.cpus = 4\n self.memoryInBytes = 1024.mib()\n self.rosetta = false\n self.nestedVirtualization = false\n self.mounts = []\n self.interfaces = []\n }\n }\n\n private nonisolated(unsafe) let vm: VZVirtualMachine\n private let queue: DispatchQueue\n private let group: MultiThreadedEventLoopGroup\n private let lock: AsyncLock\n private let timeSyncer: TimeSyncer\n private let logger: Logger?\n\n public init(\n group: MultiThreadedEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount),\n logger: Logger? = nil,\n with: (inout Configuration) throws -> Void\n ) throws {\n var config = Configuration()\n try with(&config)\n try self.init(group: group, config: config, logger: logger)\n }\n\n init(group: MultiThreadedEventLoopGroup, config: Configuration, logger: Logger?) throws {\n self.config = config\n self.group = group\n self.lock = .init()\n self.queue = DispatchQueue(label: \"com.apple.containerization.sandbox.\\(UUID().uuidString)\")\n self.mounts = try config.mountAttachments()\n self.logger = logger\n self.timeSyncer = .init(logger: logger)\n\n self.vm = VZVirtualMachine(\n configuration: try config.toVZ(),\n queue: self.queue\n )\n }\n}\n\nextension VZVirtualMachineInstance {\n func vzStateToInstanceState() -> VirtualMachineInstanceState {\n self.queue.sync {\n let state: VirtualMachineInstanceState\n switch self.vm.state {\n case .starting:\n state = .starting\n case .running:\n state = .running\n case .stopping:\n state = .stopping\n case .stopped:\n state = .stopped\n default:\n state = .unknown\n }\n return state\n }\n }\n\n func start() async throws {\n try await lock.withLock { _ in\n guard self.state == .stopped else {\n throw ContainerizationError(\n .invalidState,\n message: \"sandbox is not stopped \\(self.state)\"\n )\n }\n\n // Do any necessary setup needed prior to starting the guest.\n try await self.prestart()\n\n try await self.vm.start(queue: self.queue)\n\n let agent = Vminitd(\n connection: try await self.vm.waitForAgent(queue: self.queue),\n group: self.group\n )\n\n do {\n if self.config.rosetta {\n try await agent.enableRosetta()\n }\n } catch {\n try await agent.close()\n throw error\n }\n\n // Don't close our remote context as we are providing\n // it to our time sync routine.\n await self.timeSyncer.start(context: agent)\n }\n }\n\n func stop() async throws {\n try await lock.withLock { _ in\n // NOTE: We should record HOW the vm stopped eventually. If the vm exited\n // unexpectedly virtualization framework offers you a way to store\n // an error on how it exited. We should report that here instead of the\n // generic vm is not running.\n guard self.state == .running else {\n throw ContainerizationError(.invalidState, message: \"vm is not running\")\n }\n\n try await self.timeSyncer.close()\n\n try await self.vm.stop(queue: self.queue)\n try await self.group.shutdownGracefully()\n }\n }\n\n public func dialAgent() async throws -> Vminitd {\n let conn = try await dial(Vminitd.port)\n return Vminitd(connection: conn, group: self.group)\n }\n}\n\nextension VZVirtualMachineInstance {\n func dial(_ port: UInt32) async throws -> FileHandle {\n try await vm.connect(\n queue: queue,\n port: port\n ).dupHandle()\n }\n\n func listen(_ port: UInt32) throws -> VsockConnectionStream {\n let stream = VsockConnectionStream(port: port)\n let listener = VZVirtioSocketListener()\n listener.delegate = stream\n\n try self.vm.listen(\n queue: queue,\n port: port,\n listener: listener\n )\n return stream\n }\n\n func stopListen(_ port: UInt32) throws {\n try self.vm.removeListener(\n queue: queue,\n port: port\n )\n }\n\n func prestart() async throws {\n if self.config.rosetta {\n #if arch(arm64)\n if VZLinuxRosettaDirectoryShare.availability == .notInstalled {\n self.logger?.info(\"installing rosetta\")\n try await VZVirtualMachineInstance.Configuration.installRosetta()\n }\n #else\n fatalError(\"rosetta is only supported on arm64\")\n #endif\n }\n }\n}\n\nextension VZVirtualMachineInstance.Configuration {\n public static func installRosetta() async throws {\n do {\n #if arch(arm64)\n try await VZLinuxRosettaDirectoryShare.installRosetta()\n #else\n fatalError(\"rosetta is only supported on arm64\")\n #endif\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to install rosetta\",\n cause: error\n )\n }\n }\n\n private func serialPort(path: URL) throws -> [VZVirtioConsoleDeviceSerialPortConfiguration] {\n let c = VZVirtioConsoleDeviceSerialPortConfiguration()\n c.attachment = try VZFileSerialPortAttachment(url: path, append: true)\n return [c]\n }\n\n func toVZ() throws -> VZVirtualMachineConfiguration {\n var config = VZVirtualMachineConfiguration()\n\n config.cpuCount = self.cpus\n config.memorySize = self.memoryInBytes\n config.entropyDevices = [VZVirtioEntropyDeviceConfiguration()]\n config.socketDevices = [VZVirtioSocketDeviceConfiguration()]\n if let bootlog = self.bootlog {\n config.serialPorts = try serialPort(path: bootlog)\n }\n\n config.networkDevices = try self.interfaces.map {\n guard let vzi = $0 as? VZInterface else {\n throw ContainerizationError(.invalidArgument, message: \"interface type not supported by VZ\")\n }\n return try vzi.device()\n }\n\n if self.rosetta {\n #if arch(arm64)\n switch VZLinuxRosettaDirectoryShare.availability {\n case .notSupported:\n throw ContainerizationError(\n .invalidArgument,\n message: \"rosetta was requested but is not supported on this machine\"\n )\n case .notInstalled:\n // NOTE: If rosetta isn't installed, we'll error with a nice error message\n // during .start() of the virtual machine instance.\n fallthrough\n case .installed:\n let share = try VZLinuxRosettaDirectoryShare()\n let device = VZVirtioFileSystemDeviceConfiguration(tag: \"rosetta\")\n device.share = share\n config.directorySharingDevices.append(device)\n @unknown default:\n throw ContainerizationError(\n .invalidArgument,\n message: \"unknown rosetta availability encountered: \\(VZLinuxRosettaDirectoryShare.availability)\"\n )\n }\n #else\n fatalError(\"rosetta is only supported on arm64\")\n #endif\n }\n\n guard let kernel = self.kernel else {\n throw ContainerizationError(.invalidArgument, message: \"kernel cannot be nil\")\n }\n\n guard let initialFilesystem = self.initialFilesystem else {\n throw ContainerizationError(.invalidArgument, message: \"rootfs cannot be nil\")\n }\n\n let loader = VZLinuxBootLoader(kernelURL: kernel.path)\n loader.commandLine = kernel.linuxCommandline(initialFilesystem: initialFilesystem)\n config.bootLoader = loader\n\n try initialFilesystem.configure(config: &config)\n for mount in self.mounts {\n try mount.configure(config: &config)\n }\n\n let platform = VZGenericPlatformConfiguration()\n // We shouldn't silently succeed if the user asked for virt and their hardware does\n // not support it.\n if !VZGenericPlatformConfiguration.isNestedVirtualizationSupported && self.nestedVirtualization {\n throw ContainerizationError(\n .unsupported,\n message: \"nested virtualization is not supported on the platform\"\n )\n }\n platform.isNestedVirtualizationEnabled = self.nestedVirtualization\n config.platform = platform\n\n try config.validate()\n return config\n }\n\n func mountAttachments() throws -> [AttachedFilesystem] {\n let allocator = Character.blockDeviceTagAllocator()\n if let initialFilesystem {\n // When the initial filesystem is a blk, allocate the first letter \"vd(a)\"\n // as that is what this blk will be attached under.\n if initialFilesystem.isBlock {\n _ = try allocator.allocate()\n }\n }\n\n var attachments: [AttachedFilesystem] = []\n for mount in self.mounts {\n attachments.append(try .init(mount: mount, allocator: allocator))\n }\n return attachments\n }\n}\n\nextension Mount {\n var isBlock: Bool {\n type == \"ext4\"\n }\n}\n\nextension Kernel {\n func linuxCommandline(initialFilesystem: Mount) -> String {\n var args = self.commandLine.kernelArgs\n\n args.append(\"init=/sbin/vminitd\")\n // rootfs is always set as ro.\n args.append(\"ro\")\n\n switch initialFilesystem.type {\n case \"virtiofs\":\n args.append(contentsOf: [\n \"rootfstype=virtiofs\",\n \"root=rootfs\",\n ])\n case \"ext4\":\n args.append(contentsOf: [\n \"rootfstype=ext4\",\n \"root=/dev/vda\",\n ])\n default:\n fatalError(\"unsupported initfs filesystem \\(initialFilesystem.type)\")\n }\n\n if self.commandLine.initArgs.count > 0 {\n args.append(\"--\")\n args.append(contentsOf: self.commandLine.initArgs)\n }\n\n return args.joined(separator: \" \")\n }\n}\n\npublic protocol VZInterface {\n func device() throws -> VZVirtioNetworkDeviceConfiguration\n}\n\nextension NATInterface: VZInterface {\n public func device() throws -> VZVirtioNetworkDeviceConfiguration {\n let config = VZVirtioNetworkDeviceConfiguration()\n if let macAddress = self.macAddress {\n guard let mac = VZMACAddress(string: macAddress) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid mac address \\(macAddress)\")\n }\n config.macAddress = mac\n }\n config.attachment = VZNATNetworkDeviceAttachment()\n return config\n }\n}\n\n#endif\n"], ["/containerization/Sources/Containerization/LinuxContainer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport Logging\nimport Synchronization\n\nimport struct ContainerizationOS.Terminal\n\n/// `LinuxContainer` is an easy to use type for launching and managing the\n/// full lifecycle of a Linux container ran inside of a virtual machine.\npublic final class LinuxContainer: Container, Sendable {\n /// The default PATH value for a process.\n public static let defaultPath = \"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\n\n /// The identifier of the container.\n public let id: String\n\n /// Rootfs for the container.\n public let rootfs: Mount\n\n /// Configuration for the container.\n public let config: Configuration\n\n /// The configuration for the LinuxContainer.\n public struct Configuration: Sendable {\n /// Configuration of a container process.\n public struct Process: Sendable {\n /// The arguments for the container process.\n public var arguments: [String] = []\n /// The environment variables for the container process.\n public var environmentVariables: [String] = [\"PATH=\\(LinuxContainer.defaultPath)\"]\n /// The working directory for the container process.\n public var workingDirectory: String = \"/\"\n /// The user the container process will run as.\n public var user: ContainerizationOCI.User = .init()\n /// The rlimits for the container process.\n public var rlimits: [POSIXRlimit] = []\n /// Whether to allocate a pseudo terminal for the process. If you'd like interactive\n /// behavior and are planning to use a terminal for stdin/out/err on the client side,\n /// this should likely be set to true.\n public var terminal: Bool = false\n /// The stdin for the process.\n public var stdin: ReaderStream?\n /// The stdout for the process.\n public var stdout: Writer?\n /// The stderr for the process.\n public var stderr: Writer?\n\n public init() {}\n\n public init(from config: ImageConfig) {\n self.workingDirectory = config.workingDir ?? \"/\"\n self.environmentVariables = config.env ?? []\n self.arguments = (config.entrypoint ?? []) + (config.cmd ?? [])\n self.user = {\n if let rawString = config.user {\n return User(username: rawString)\n }\n return User()\n }()\n }\n\n func toOCI() -> ContainerizationOCI.Process {\n ContainerizationOCI.Process(\n args: self.arguments,\n cwd: self.workingDirectory,\n env: self.environmentVariables,\n user: self.user,\n rlimits: self.rlimits,\n terminal: self.terminal\n )\n }\n\n /// Sets up IO to be handled by the passed in Terminal, and edits the\n /// process configuration to set the necessary state for using a pty.\n mutating public func setTerminalIO(terminal: Terminal) {\n self.environmentVariables.append(\"TERM=xterm\")\n self.terminal = true\n self.stdin = terminal\n self.stdout = terminal\n }\n }\n\n /// Configuration for the init process of the container.\n public var process = Process.init()\n /// The amount of cpus for the container.\n public var cpus: Int = 4\n /// The memory in bytes to give to the container.\n public var memoryInBytes: UInt64 = 1024.mib()\n /// The hostname for the container.\n public var hostname: String = \"\"\n /// The system control options for the container.\n public var sysctl: [String: String] = [:]\n /// The network interfaces for the container.\n public var interfaces: [any Interface] = []\n /// The Unix domain socket relays to setup for the container.\n public var sockets: [UnixSocketConfiguration] = []\n /// Whether rosetta x86-64 emulation should be setup for the container.\n public var rosetta: Bool = false\n /// Whether nested virtualization should be turned on for the container.\n public var virtualization: Bool = false\n /// The mounts for the container.\n public var mounts: [Mount] = LinuxContainer.defaultMounts()\n /// The DNS configuration for the container.\n public var dns: DNS?\n /// The hosts to add to /etc/hosts for the container.\n public var hosts: Hosts?\n\n public init() {}\n }\n\n /// `IOHandler` informs the container process about what should be done\n /// for the stdio streams.\n struct IOHandler: Sendable {\n public var stdin: ReaderStream?\n public var stdout: Writer?\n public var stderr: Writer?\n\n init(stdin: ReaderStream? = nil, stdout: Writer? = nil, stderr: Writer? = nil) {\n self.stdin = stdin\n self.stdout = stdout\n self.stderr = stderr\n }\n }\n\n private let state: Mutex\n\n // Ports to be allocated from for stdio and for\n // unix socket relays that are sharing a guest\n // uds to the host.\n private let hostVsockPorts: Atomic\n // Ports we request the guest to allocate for unix socket relays from\n // the host.\n private let guestVsockPorts: Atomic\n\n private enum State: Sendable {\n /// The container class has been created but no live resources are running.\n case initialized\n /// The container is creating and booting the underlying virtual resources.\n case creating(CreatingState)\n /// The container's virtual machine has been setup and the runtime environment has been configured.\n case created(CreatedState)\n /// The initial process of the container is preparing to start.\n case starting(StartingState)\n /// The initial process of the container has started and is running.\n case started(StartedState)\n /// The container is preparing to stop.\n case stopping(StoppingState)\n /// The container has run and fully stopped.\n case stopped\n /// An error occurred during the lifetime of this class.\n case errored(Swift.Error)\n\n struct CreatingState: Sendable {}\n\n struct CreatedState: Sendable {\n let vm: any VirtualMachineInstance\n let relayManager: UnixSocketRelayManager\n }\n\n struct StartingState: Sendable {\n let vm: any VirtualMachineInstance\n let relayManager: UnixSocketRelayManager\n\n init(_ state: CreatedState) {\n self.vm = state.vm\n self.relayManager = state.relayManager\n }\n }\n\n struct StartedState: Sendable {\n let vm: any VirtualMachineInstance\n let process: LinuxProcess\n let relayManager: UnixSocketRelayManager\n\n init(_ state: StartingState, process: LinuxProcess) {\n self.vm = state.vm\n self.relayManager = state.relayManager\n self.process = process\n }\n }\n\n struct StoppingState: Sendable {\n let vm: any VirtualMachineInstance\n\n init(_ state: StartedState) {\n self.vm = state.vm\n }\n }\n\n mutating func setCreating() throws {\n switch self {\n case .initialized:\n self = .creating(.init())\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in initialized state to start\"\n )\n }\n }\n\n mutating func setCreated(\n vm: any VirtualMachineInstance,\n relayManager: UnixSocketRelayManager\n ) throws {\n switch self {\n case .creating:\n self = .created(.init(vm: vm, relayManager: relayManager))\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in creating state before created\"\n )\n }\n }\n\n mutating func setStarting() throws -> any VirtualMachineInstance {\n switch self {\n case .created(let state):\n self = .starting(.init(state))\n return state.vm\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in created state before starting\"\n )\n }\n }\n\n mutating func setStarted(process: LinuxProcess) throws {\n switch self {\n case .starting(let state):\n self = .started(.init(state, process: process))\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in starting state before started\"\n )\n }\n }\n\n mutating func stopping() throws -> StartedState {\n switch self {\n case .started(let state):\n self = .stopping(.init(state))\n return state\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in a started state before stopping\"\n )\n }\n }\n\n func startedState(_ operation: String) throws -> StartedState {\n switch self {\n case .started(let state):\n return state\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"failed to \\(operation): container must be running\"\n )\n }\n }\n\n mutating func stopped() throws {\n switch self {\n case .stopping(_):\n self = .stopped\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in a stopping state before setting to stopped\"\n )\n }\n }\n\n mutating func errored(error: Swift.Error) {\n self = .errored(error)\n }\n }\n\n private let vmm: VirtualMachineManager\n private let logger: Logger?\n\n /// Create a new `LinuxContainer`. A `Mount` that contains the contents\n /// of the container image must be provided, as well as a `VirtualMachineManager`\n /// instance that will handle launching the virtual machine the container will\n /// execute inside of.\n public init(\n _ id: String,\n rootfs: Mount,\n vmm: VirtualMachineManager,\n logger: Logger? = nil,\n configuration: (inout Configuration) throws -> Void\n ) throws {\n self.id = id\n self.vmm = vmm\n self.hostVsockPorts = Atomic(0x1000_0000)\n self.guestVsockPorts = Atomic(0x1000_0000)\n self.rootfs = rootfs\n self.logger = logger\n\n var config = Configuration()\n try configuration(&config)\n\n self.config = config\n self.state = Mutex(.initialized)\n }\n\n private static func createDefaultRuntimeSpec(_ id: String) -> Spec {\n .init(\n process: .init(),\n hostname: id,\n root: .init(\n path: Self.guestRootfsPath(id),\n readonly: false\n ),\n linux: .init(\n resources: .init()\n )\n )\n }\n\n private func generateRuntimeSpec() -> Spec {\n var spec = Self.createDefaultRuntimeSpec(id)\n\n // Process toggles.\n spec.process = config.process.toOCI()\n\n // General toggles.\n spec.hostname = config.hostname\n\n // Linux toggles.\n var linux = ContainerizationOCI.Linux.init()\n linux.sysctl = config.sysctl\n spec.linux = linux\n\n return spec\n }\n\n public static func defaultMounts() -> [Mount] {\n let defaultOptions = [\"nosuid\", \"noexec\", \"nodev\"]\n return [\n .any(type: \"proc\", source: \"proc\", destination: \"/proc\", options: defaultOptions),\n .any(type: \"sysfs\", source: \"sysfs\", destination: \"/sys\", options: defaultOptions),\n .any(type: \"devtmpfs\", source: \"none\", destination: \"/dev\", options: [\"nosuid\", \"mode=755\"]),\n .any(type: \"mqueue\", source: \"mqueue\", destination: \"/dev/mqueue\", options: defaultOptions),\n .any(type: \"tmpfs\", source: \"tmpfs\", destination: \"/dev/shm\", options: defaultOptions + [\"mode=1777\", \"size=65536k\"]),\n .any(type: \"cgroup2\", source: \"none\", destination: \"/sys/fs/cgroup\", options: defaultOptions),\n .any(type: \"devpts\", source: \"devpts\", destination: \"/dev/pts\", options: [\"nosuid\", \"noexec\", \"gid=5\", \"mode=620\", \"ptmxmode=666\"]),\n ]\n }\n\n private static func guestRootfsPath(_ id: String) -> String {\n \"/run/container/\\(id)/rootfs\"\n }\n}\n\nextension LinuxContainer {\n package var root: String {\n Self.guestRootfsPath(id)\n }\n\n /// Number of CPU cores allocated.\n public var cpus: Int {\n config.cpus\n }\n\n /// Amount of memory in bytes allocated for the container.\n /// This will be aligned to a 1MB boundary if it isn't already.\n public var memoryInBytes: UInt64 {\n config.memoryInBytes\n }\n\n /// Network interfaces of the container.\n public var interfaces: [any Interface] {\n config.interfaces\n }\n\n /// Create the underlying container's virtual machine\n /// and set up the runtime environment.\n public func create() async throws {\n try self.state.withLock { try $0.setCreating() }\n\n let vm = try vmm.create(container: self)\n try await vm.start()\n do {\n try await vm.withAgent { agent in\n let relayManager = UnixSocketRelayManager(vm: vm)\n\n try await agent.standardSetup()\n\n // Mount the rootfs.\n var rootfs = vm.mounts[0].to\n rootfs.destination = Self.guestRootfsPath(self.id)\n try await agent.mount(rootfs)\n\n // Start up our friendly unix socket relays.\n for socket in self.config.sockets {\n try await self.relayUnixSocket(\n socket: socket,\n relayManager: relayManager,\n agent: agent\n )\n }\n\n // For every interface asked for:\n // 1. Add the address requested\n // 2. Online the adapter\n // 3. If a gateway IP address is present, add the default route.\n for (index, i) in self.interfaces.enumerated() {\n let name = \"eth\\(index)\"\n try await agent.addressAdd(name: name, address: i.address)\n try await agent.up(name: name, mtu: 1280)\n if let gateway = i.gateway {\n try await agent.routeAddDefault(name: name, gateway: gateway)\n }\n }\n\n // Setup /etc/resolv.conf and /etc/hosts if asked for.\n if let dns = self.config.dns {\n try await agent.configureDNS(config: dns, location: rootfs.destination)\n }\n if let hosts = self.config.hosts {\n try await agent.configureHosts(config: hosts, location: rootfs.destination)\n }\n\n try self.state.withLock { try $0.setCreated(vm: vm, relayManager: relayManager) }\n }\n } catch {\n try? await vm.stop()\n self.state.withLock { $0.errored(error: error) }\n throw error\n }\n }\n\n /// Start the container container's initial process.\n public func start() async throws {\n let vm = try self.state.withLock { try $0.setStarting() }\n\n let agent = try await vm.dialAgent()\n do {\n var spec = generateRuntimeSpec()\n // We don't need the rootfs, nor do OCI runtimes want it included.\n spec.mounts = vm.mounts.dropFirst().map { $0.to }\n\n let stdio = Self.setupIO(\n portAllocator: self.hostVsockPorts,\n stdin: self.config.process.stdin,\n stdout: self.config.process.stdout,\n stderr: self.config.process.stderr\n )\n\n let process = LinuxProcess(\n self.id,\n containerID: self.id,\n spec: spec,\n io: stdio,\n agent: agent,\n vm: vm,\n logger: self.logger\n )\n try await process.start()\n\n try self.state.withLock { try $0.setStarted(process: process) }\n } catch {\n try? await agent.close()\n self.state.withLock { $0.errored(error: error) }\n throw error\n }\n }\n\n private static func setupIO(\n portAllocator: borrowing Atomic,\n stdin: ReaderStream?,\n stdout: Writer?,\n stderr: Writer?\n ) -> LinuxProcess.Stdio {\n var stdinSetup: LinuxProcess.StdioReaderSetup? = nil\n if let reader = stdin {\n let ret = portAllocator.wrappingAdd(1, ordering: .relaxed)\n stdinSetup = .init(\n port: ret.oldValue,\n reader: reader\n )\n }\n\n var stdoutSetup: LinuxProcess.StdioSetup? = nil\n if let writer = stdout {\n let ret = portAllocator.wrappingAdd(1, ordering: .relaxed)\n stdoutSetup = LinuxProcess.StdioSetup(\n port: ret.oldValue,\n writer: writer\n )\n }\n\n var stderrSetup: LinuxProcess.StdioSetup? = nil\n if let writer = stderr {\n let ret = portAllocator.wrappingAdd(1, ordering: .relaxed)\n stderrSetup = LinuxProcess.StdioSetup(\n port: ret.oldValue,\n writer: writer\n )\n }\n\n return LinuxProcess.Stdio(\n stdin: stdinSetup,\n stdout: stdoutSetup,\n stderr: stderrSetup\n )\n }\n\n /// Stop the container from executing.\n public func stop() async throws {\n let startedState = try self.state.withLock { try $0.stopping() }\n\n try await startedState.relayManager.stopAll()\n\n // It's possible the state of the vm is not in a great spot\n // if the guest panicked or had any sort of bug/fault.\n // First check if the vm is even still running, as trying to\n // use a vsock handle like below here will cause NIO to\n // fatalError because we'll get an EBADF.\n if startedState.vm.state == .stopped {\n try self.state.withLock { try $0.stopped() }\n return\n }\n\n try await startedState.vm.withAgent { agent in\n // First, we need to stop any unix socket relays as this will\n // keep the rootfs from being able to umount (EBUSY).\n let sockets = config.sockets\n if !sockets.isEmpty {\n guard let relayAgent = agent as? SocketRelayAgent else {\n throw ContainerizationError(\n .unsupported,\n message: \"VirtualMachineAgent does not support relaySocket surface\"\n )\n }\n for socket in sockets {\n try await relayAgent.stopSocketRelay(configuration: socket)\n }\n }\n\n // Now lets ensure every process is donezo.\n try await agent.kill(pid: -1, signal: SIGKILL)\n\n // Wait on init proc exit. Give it 5 seconds of leeway.\n _ = try await agent.waitProcess(\n id: self.id,\n containerID: self.id,\n timeoutInSeconds: 5\n )\n\n // Today, we leave EBUSY looping and other fun logic up to the\n // guest agent.\n try await agent.umount(\n path: Self.guestRootfsPath(self.id),\n flags: 0\n )\n }\n\n // Lets free up the init procs resources, as this includes the open agent conn.\n try? await startedState.process.delete()\n\n try await startedState.vm.stop()\n try self.state.withLock { try $0.stopped() }\n }\n\n /// Send a signal to the container.\n public func kill(_ signal: Int32) async throws {\n let state = try self.state.withLock { try $0.startedState(\"kill\") }\n try await state.process.kill(signal)\n }\n\n /// Wait for the container to exit. Returns the exit code.\n @discardableResult\n public func wait(timeoutInSeconds: Int64? = nil) async throws -> Int32 {\n let state = try self.state.withLock { try $0.startedState(\"wait\") }\n return try await state.process.wait(timeoutInSeconds: timeoutInSeconds)\n }\n\n /// Resize the container's terminal (if one was requested). This\n /// will error if terminal was set to false before creating the container.\n public func resize(to: Terminal.Size) async throws {\n let state = try self.state.withLock { try $0.startedState(\"resize\") }\n try await state.process.resize(to: to)\n }\n\n /// Execute a new process in the container.\n public func exec(_ id: String, configuration: (inout Configuration.Process) throws -> Void) async throws -> LinuxProcess {\n let state = try self.state.withLock { try $0.startedState(\"exec\") }\n\n var spec = generateRuntimeSpec()\n var config = Configuration.Process()\n try configuration(&config)\n spec.process = config.toOCI()\n\n let stdio = Self.setupIO(\n portAllocator: self.hostVsockPorts,\n stdin: config.stdin,\n stdout: config.stdout,\n stderr: config.stderr\n )\n let agent = try await state.vm.dialAgent()\n let process = LinuxProcess(\n id,\n containerID: self.id,\n spec: spec,\n io: stdio,\n agent: agent,\n vm: state.vm,\n logger: self.logger\n )\n return process\n }\n\n /// Execute a new process in the container.\n public func exec(_ id: String, configuration: Configuration.Process) async throws -> LinuxProcess {\n let state = try self.state.withLock { try $0.startedState(\"exec\") }\n\n var spec = generateRuntimeSpec()\n spec.process = configuration.toOCI()\n\n let stdio = Self.setupIO(\n portAllocator: self.hostVsockPorts,\n stdin: configuration.stdin,\n stdout: configuration.stdout,\n stderr: configuration.stderr\n )\n let agent = try await state.vm.dialAgent()\n let process = LinuxProcess(\n id,\n containerID: self.id,\n spec: spec,\n io: stdio,\n agent: agent,\n vm: state.vm,\n logger: self.logger\n )\n return process\n }\n\n /// Dial a vsock port in the container.\n public func dialVsock(port: UInt32) async throws -> FileHandle {\n let state = try self.state.withLock { try $0.startedState(\"dialVsock\") }\n return try await state.vm.dial(port)\n }\n\n /// Close the containers standard input to signal no more input is\n /// arriving.\n public func closeStdin() async throws {\n let state = try self.state.withLock { try $0.startedState(\"closeStdin\") }\n return try await state.process.closeStdin()\n }\n\n /// Relay a unix socket from in the container to the host, or from the host\n /// to inside the container.\n public func relayUnixSocket(socket: UnixSocketConfiguration) async throws {\n let state = try self.state.withLock { try $0.startedState(\"relayUnixSocket\") }\n\n try await state.vm.withAgent { agent in\n try await self.relayUnixSocket(\n socket: socket,\n relayManager: state.relayManager,\n agent: agent\n )\n }\n }\n\n private func relayUnixSocket(\n socket: UnixSocketConfiguration,\n relayManager: UnixSocketRelayManager,\n agent: any VirtualMachineAgent\n ) async throws {\n guard let relayAgent = agent as? SocketRelayAgent else {\n throw ContainerizationError(\n .unsupported,\n message: \"VirtualMachineAgent does not support relaySocket surface\"\n )\n }\n\n var socket = socket\n let rootInGuest = URL(filePath: self.root)\n\n if socket.direction == .into {\n socket.destination = rootInGuest.appending(path: socket.destination.path)\n } else {\n socket.source = rootInGuest.appending(path: socket.source.path)\n }\n\n let port = self.hostVsockPorts.wrappingAdd(1, ordering: .relaxed).oldValue\n try await relayManager.start(port: port, socket: socket)\n try await relayAgent.relaySocket(port: port, configuration: socket)\n }\n}\n\nextension VirtualMachineInstance {\n /// Scoped access to an agent instance to ensure the resources are always freed (mostly close(2)'ing\n /// the vsock fd)\n fileprivate func withAgent(fn: @Sendable (VirtualMachineAgent) async throws -> Void) async throws {\n let agent = try await self.dialAgent()\n do {\n try await fn(agent)\n try await agent.close()\n } catch {\n try? await agent.close()\n throw error\n }\n }\n}\n\nextension AttachedFilesystem {\n fileprivate var to: ContainerizationOCI.Mount {\n .init(\n type: self.type,\n source: self.source,\n destination: self.destination,\n options: self.options\n )\n }\n}\n\n#endif\n"], ["/containerization/vminitd/Sources/vminitd/Server+GRPC.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport ContainerizationNetlink\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport GRPC\nimport Logging\nimport NIOCore\nimport NIOPosix\nimport _NIOFileSystem\n\nprivate let _setenv = Foundation.setenv\n\n#if canImport(Musl)\nimport Musl\nprivate let _mount = Musl.mount\nprivate let _umount = Musl.umount2\nprivate let _kill = Musl.kill\nprivate let _sync = Musl.sync\n#elseif canImport(Glibc)\nimport Glibc\nprivate let _mount = Glibc.mount\nprivate let _umount = Glibc.umount2\nprivate let _kill = Glibc.kill\nprivate let _sync = Glibc.sync\n#endif\n\nextension Initd: Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncProvider {\n func setTime(\n request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetTimeResponse {\n log.debug(\n \"setTime\",\n metadata: [\n \"sec\": \"\\(request.sec)\",\n \"usec\": \"\\(request.usec)\",\n ])\n\n var tv = timeval(tv_sec: time_t(request.sec), tv_usec: suseconds_t(request.usec))\n guard settimeofday(&tv, nil) == 0 else {\n let error = swiftErrno(\"settimeofday\")\n log.error(\n \"setTime\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"failed to settimeofday: \\(error)\")\n }\n\n return .init()\n }\n\n func setupEmulator(\n request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse {\n log.debug(\n \"setupEmulator\",\n metadata: [\n \"request\": \"\\(request)\"\n ])\n\n if !Binfmt.mounted() {\n throw GRPCStatus(\n code: .internalError,\n message: \"\\(Binfmt.path) is not mounted\"\n )\n }\n\n do {\n let bfmt = Binfmt.Entry(\n name: request.name,\n type: request.type,\n offset: request.offset,\n magic: request.magic,\n mask: request.mask,\n flags: request.flags\n )\n try bfmt.register(binaryPath: request.binaryPath)\n } catch {\n log.error(\n \"setupEmulator\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"setupEmulator: failed to register binfmt_misc entry: \\(error)\"\n )\n }\n\n return .init()\n }\n\n func sysctl(\n request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SysctlResponse {\n log.debug(\n \"sysctl\",\n metadata: [\n \"settings\": \"\\(request.settings)\"\n ])\n\n do {\n let sysctlPath = URL(fileURLWithPath: \"/proc/sys/\")\n for (k, v) in request.settings {\n guard let data = v.data(using: .ascii) else {\n throw GRPCStatus(code: .internalError, message: \"failed to convert \\(v) to data buffer for sysctl write\")\n }\n\n let setting =\n sysctlPath\n .appendingPathComponent(k.replacingOccurrences(of: \".\", with: \"/\"))\n let fh = try FileHandle(forWritingTo: setting)\n defer { try? fh.close() }\n\n try fh.write(contentsOf: data)\n }\n } catch {\n log.error(\n \"sysctl\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"sysctl: failed to set sysctl: \\(error)\"\n )\n }\n\n return .init()\n }\n\n func proxyVsock(\n request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse {\n log.debug(\n \"proxyVsock\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"port\": \"\\(request.vsockPort)\",\n \"guestPath\": \"\\(request.guestPath)\",\n \"action\": \"\\(request.action)\",\n ])\n\n do {\n let proxy = VsockProxy(\n id: request.id,\n action: request.action == .into ? .dial : .listen,\n port: request.vsockPort,\n path: URL(fileURLWithPath: request.guestPath),\n udsPerms: request.guestSocketPermissions,\n log: log\n )\n\n try proxy.start()\n try await state.add(proxy: proxy)\n } catch {\n log.error(\n \"proxyVsock\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"proxyVsock: failed to setup vsock proxy: \\(error)\"\n )\n }\n\n return .init()\n }\n\n func stopVsockProxy(\n request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse {\n log.debug(\n \"stopVsockProxy\",\n metadata: [\n \"id\": \"\\(request.id)\"\n ])\n\n do {\n let proxy = try await state.remove(proxy: request.id)\n try proxy.close()\n } catch {\n log.error(\n \"stopVsockProxy\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"stopVsockProxy: failed to stop vsock proxy: \\(error)\"\n )\n }\n\n return .init()\n }\n\n func mkdir(request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest, context: GRPC.GRPCAsyncServerCallContext)\n async throws -> Com_Apple_Containerization_Sandbox_V3_MkdirResponse\n {\n log.debug(\n \"mkdir\",\n metadata: [\n \"path\": \"\\(request.path)\",\n \"all\": \"\\(request.all)\",\n ])\n\n do {\n try FileManager.default.createDirectory(\n atPath: request.path,\n withIntermediateDirectories: request.all\n )\n } catch {\n log.error(\n \"mkdir\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"mkdir: \\(error)\")\n }\n\n return .init()\n }\n\n func mount(request: Com_Apple_Containerization_Sandbox_V3_MountRequest, context: GRPC.GRPCAsyncServerCallContext)\n async throws -> Com_Apple_Containerization_Sandbox_V3_MountResponse\n {\n log.debug(\n \"mount\",\n metadata: [\n \"type\": \"\\(request.type)\",\n \"source\": \"\\(request.source)\",\n \"destination\": \"\\(request.destination)\",\n ])\n\n do {\n let mnt = ContainerizationOS.Mount(\n type: request.type,\n source: request.source,\n target: request.destination,\n options: request.options\n )\n\n #if os(Linux)\n try mnt.mount(createWithPerms: 0o755)\n return .init()\n #else\n fatalError(\"mount not supported on platform\")\n #endif\n } catch {\n log.error(\n \"mount\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"mount: \\(error)\")\n }\n }\n\n func umount(request: Com_Apple_Containerization_Sandbox_V3_UmountRequest, context: GRPC.GRPCAsyncServerCallContext)\n async throws -> Com_Apple_Containerization_Sandbox_V3_UmountResponse\n {\n log.debug(\n \"umount\",\n metadata: [\n \"path\": \"\\(request.path)\",\n \"flags\": \"\\(request.flags)\",\n ])\n\n #if os(Linux)\n // Best effort EBUSY handle.\n for _ in 0...50 {\n let result = _umount(request.path, request.flags)\n if result == -1 {\n if errno == EBUSY {\n try await Task.sleep(for: .milliseconds(10))\n continue\n }\n let error = swiftErrno(\"umount\")\n\n log.error(\n \"umount\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .invalidArgument, message: \"umount: \\(error)\")\n }\n break\n }\n return .init()\n #else\n fatalError(\"umount not supported on platform\")\n #endif\n }\n\n func setenv(request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest, context: GRPC.GRPCAsyncServerCallContext)\n async throws -> Com_Apple_Containerization_Sandbox_V3_SetenvResponse\n {\n log.debug(\n \"setenv\",\n metadata: [\n \"key\": \"\\(request.key)\",\n \"value\": \"\\(request.value)\",\n ])\n\n guard _setenv(request.key, request.value, 1) == 0 else {\n let error = swiftErrno(\"setenv\")\n\n log.error(\n \"setEnv\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n\n throw GRPCStatus(code: .invalidArgument, message: \"setenv: \\(error)\")\n }\n return .init()\n }\n\n func getenv(request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest, context: GRPC.GRPCAsyncServerCallContext)\n async throws -> Com_Apple_Containerization_Sandbox_V3_GetenvResponse\n {\n log.debug(\n \"getenv\",\n metadata: [\n \"key\": \"\\(request.key)\"\n ])\n\n let env = ProcessInfo.processInfo.environment[request.key]\n return .with {\n if let env {\n $0.value = env\n }\n }\n }\n\n func createProcess(\n request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest, context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse {\n log.debug(\n \"createProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"stdin\": \"Port: \\(request.stdin)\",\n \"stdout\": \"Port: \\(request.stdout)\",\n \"stderr\": \"Port: \\(request.stderr)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n do {\n var ociSpec = try JSONDecoder().decode(\n ContainerizationOCI.Spec.self,\n from: request.configuration\n )\n\n try ociAlterations(ociSpec: &ociSpec)\n\n guard let process = ociSpec.process else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"oci runtime spec missing process configuration\"\n )\n }\n\n let stdioPorts = HostStdio(\n stdin: request.hasStdin ? request.stdin : nil,\n stdout: request.hasStdout ? request.stdout : nil,\n stderr: request.hasStderr ? request.stderr : nil,\n terminal: process.terminal\n )\n\n // This is an exec.\n if let container = await self.state.containers[request.containerID] {\n try await container.createExec(\n id: request.id,\n stdio: stdioPorts,\n process: process\n )\n } else {\n // We need to make our new fangled container.\n // The process ID must match the container ID for this.\n guard request.id == request.containerID else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"init process id must match container id\"\n )\n }\n\n // Write the etc/hostname file in the container rootfs since some init-systems\n // depend on it.\n let hostname = ociSpec.hostname\n if let root = ociSpec.root, !hostname.isEmpty {\n let etc = URL(fileURLWithPath: root.path).appendingPathComponent(\"etc\")\n try FileManager.default.createDirectory(atPath: etc.path, withIntermediateDirectories: true)\n let hostnamePath = etc.appendingPathComponent(\"hostname\")\n try hostname.write(toFile: hostnamePath.path, atomically: true, encoding: .utf8)\n }\n\n let ctr = try ManagedContainer(\n id: request.id,\n stdio: stdioPorts,\n spec: ociSpec,\n log: self.log\n )\n try await self.state.add(container: ctr)\n }\n\n return .init()\n } catch {\n log.error(\n \"createProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"error\": \"\\(error)\",\n ])\n if error is GRPCStatus {\n throw error\n }\n throw GRPCStatus(code: .internalError, message: \"create managed process: \\(error)\")\n }\n }\n\n func killProcess(\n request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillProcessResponse {\n log.debug(\n \"killProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"signal\": \"\\(request.signal)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n let ctr = try await self.state.get(container: request.containerID)\n try await ctr.kill(execID: request.id, request.signal)\n\n return .init()\n }\n\n func deleteProcess(\n request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest, context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse {\n log.debug(\n \"deleteProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n let ctr = try await self.state.get(container: request.containerID)\n\n // Are we trying to delete the container itself?\n if request.id == request.containerID {\n try await ctr.delete()\n try await state.remove(container: request.id)\n } else {\n // Or just a single exec.\n try await ctr.deleteExec(id: request.id)\n }\n\n return .init()\n }\n\n func startProcess(\n request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest, context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StartProcessResponse {\n log.debug(\n \"startProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n do {\n let ctr = try await self.state.get(container: request.containerID)\n let pid = try await ctr.start(execID: request.id)\n\n return .with {\n $0.pid = pid\n }\n } catch {\n log.error(\n \"startProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"error\": \"\\(error)\",\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"startProcess: failed to start process: \\(error)\"\n )\n }\n }\n\n func resizeProcess(\n request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest, context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse {\n log.debug(\n \"resizeProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n do {\n let ctr = try await self.state.get(container: request.containerID)\n let size = Terminal.Size(\n width: UInt16(request.columns),\n height: UInt16(request.rows)\n )\n try await ctr.resize(execID: request.id, size: size)\n } catch {\n log.error(\n \"resizeProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"error\": \"\\(error)\",\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"resizeProcess: failed to resize process: \\(error)\"\n )\n }\n\n return .init()\n }\n\n func waitProcess(\n request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest, context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse {\n log.debug(\n \"waitProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n do {\n let ctr = try await self.state.get(container: request.containerID)\n\n let exitCode = try await ctr.wait(execID: request.id)\n\n return .with {\n $0.exitCode = exitCode\n }\n } catch {\n log.error(\n \"waitProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"error\": \"\\(error)\",\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"waitProcess: failed to wait on process: \\(error)\"\n )\n }\n }\n\n func closeProcessStdin(\n request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest, context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse {\n log.debug(\n \"closeProcessStdin\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n do {\n let ctr = try await self.state.get(container: request.containerID)\n\n try await ctr.closeStdin(execID: request.id)\n\n return .init()\n } catch {\n log.error(\n \"closeProcessStdin\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"error\": \"\\(error)\",\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"closeProcessStdin: failed to close process stdin: \\(error)\"\n )\n }\n }\n\n func ipLinkSet(\n request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest, context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse {\n log.debug(\n \"ip-link-set\",\n metadata: [\n \"interface\": \"\\(request.interface)\",\n \"up\": \"\\(request.up)\",\n ])\n\n do {\n let socket = try DefaultNetlinkSocket()\n let session = NetlinkSession(socket: socket, log: log)\n let mtuValue: UInt32? = request.hasMtu ? request.mtu : nil\n try session.linkSet(interface: request.interface, up: request.up, mtu: mtuValue)\n } catch {\n log.error(\n \"ip-link-set\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"ip-link-set: \\(error)\")\n }\n\n return .init()\n }\n\n func ipAddrAdd(\n request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest, context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse {\n log.debug(\n \"ip-addr-add\",\n metadata: [\n \"interface\": \"\\(request.interface)\",\n \"addr\": \"\\(request.address)\",\n ])\n\n do {\n let socket = try DefaultNetlinkSocket()\n let session = NetlinkSession(socket: socket, log: log)\n try session.addressAdd(interface: request.interface, address: request.address)\n } catch {\n log.error(\n \"ip-addr-add\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"ip-addr-add: \\(error)\")\n }\n\n return .init()\n }\n\n func ipRouteAddLink(\n request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest, context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse {\n log.debug(\n \"ip-route-add-link\",\n metadata: [\n \"interface\": \"\\(request.interface)\",\n \"address\": \"\\(request.address)\",\n \"srcAddr\": \"\\(request.srcAddr)\",\n ])\n\n do {\n let socket = try DefaultNetlinkSocket()\n let session = NetlinkSession(socket: socket, log: log)\n try session.routeAdd(\n interface: request.interface,\n destinationAddress: request.address,\n srcAddr: request.srcAddr\n )\n } catch {\n log.error(\n \"ip-route-add-link\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"ip-route-add-link: \\(error)\")\n }\n\n return .init()\n }\n\n func ipRouteAddDefault(\n request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse {\n log.debug(\n \"ip-route-add-default\",\n metadata: [\n \"interface\": \"\\(request.interface)\",\n \"gateway\": \"\\(request.gateway)\",\n ])\n\n do {\n let socket = try DefaultNetlinkSocket()\n let session = NetlinkSession(socket: socket, log: log)\n try session.routeAddDefault(interface: request.interface, gateway: request.gateway)\n } catch {\n log.error(\n \"ip-route-add-default\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"ip-route-add-default: \\(error)\")\n }\n\n return .init()\n }\n\n func configureDns(\n request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse {\n let domain = request.hasDomain ? request.domain : nil\n log.debug(\n \"configure-dns\",\n metadata: [\n \"location\": \"\\(request.location)\",\n \"nameservers\": \"\\(request.nameservers)\",\n \"domain\": \"\\(domain ?? \"\")\",\n ])\n\n do {\n let etc = URL(fileURLWithPath: request.location).appendingPathComponent(\"etc\")\n try FileManager.default.createDirectory(atPath: etc.path, withIntermediateDirectories: true)\n let resolvConf = etc.appendingPathComponent(\"resolv.conf\")\n let config = DNS(\n nameservers: request.nameservers,\n domain: domain,\n searchDomains: request.searchDomains,\n options: request.options\n )\n let text = config.resolvConf\n log.debug(\"writing to path \\(resolvConf.path) \\(text)\")\n try text.write(toFile: resolvConf.path, atomically: true, encoding: .utf8)\n log.debug(\"wrote resolver configuration\", metadata: [\"path\": \"\\(resolvConf.path)\"])\n } catch {\n log.error(\n \"configure-dns\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"configure-dns: \\(error)\")\n }\n\n return .init()\n }\n\n func configureHosts(\n request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse {\n log.debug(\n \"configureHosts\",\n metadata: [\n \"location\": \"\\(request.location)\"\n ])\n\n do {\n let etc = URL(fileURLWithPath: request.location).appendingPathComponent(\"etc\")\n try FileManager.default.createDirectory(atPath: etc.path, withIntermediateDirectories: true)\n let hostsPath = etc.appendingPathComponent(\"hosts\")\n\n let config = request.toCZHosts()\n let text = config.hostsFile\n try text.write(toFile: hostsPath.path, atomically: true, encoding: .utf8)\n\n log.debug(\"wrote /etc/hosts configuration\", metadata: [\"path\": \"\\(hostsPath.path)\"])\n } catch {\n log.error(\n \"configureHosts\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"configureHosts: \\(error)\")\n }\n\n return .init()\n }\n\n private func swiftErrno(_ msg: Logger.Message) -> POSIXError {\n let error = POSIXError(.init(rawValue: errno)!)\n log.error(\n msg,\n metadata: [\n \"error\": \"\\(error)\"\n ])\n return error\n }\n\n func sync(\n request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SyncResponse {\n log.debug(\"sync\")\n\n _sync()\n return .init()\n }\n\n func kill(\n request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillResponse {\n log.debug(\n \"kill\",\n metadata: [\n \"pid\": \"\\(request.pid)\",\n \"signal\": \"\\(request.signal)\",\n ])\n\n let r = _kill(request.pid, request.signal)\n return .with {\n $0.result = r\n }\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest {\n func toCZHosts() -> Hosts {\n let entries = self.entries.map {\n Hosts.Entry(\n ipAddress: $0.ipAddress,\n hostnames: $0.hostnames,\n comment: $0.hasComment ? $0.comment : nil\n )\n }\n return Hosts(\n entries: entries,\n comment: self.hasComment ? self.comment : nil\n )\n }\n}\n\nextension Initd {\n func ociAlterations(ociSpec: inout ContainerizationOCI.Spec) throws {\n guard var process = ociSpec.process else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"runtime spec without process field present\"\n )\n }\n guard let root = ociSpec.root else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"runtime spec without root field present\"\n )\n }\n\n if process.cwd.isEmpty {\n process.cwd = \"/\"\n }\n\n // Username is truthfully a Windows field, but we use this as away to pass through\n // the exact string representation of a username a client may have given us.\n let username = process.user.username.isEmpty ? \"\\(process.user.uid):\\(process.user.gid)\" : process.user.username\n let parsedUser = try User.parseUser(root: root.path, userString: username)\n process.user.uid = parsedUser.uid\n process.user.gid = parsedUser.gid\n process.user.additionalGids = parsedUser.sgids\n if !process.env.contains(where: { $0.hasPrefix(\"HOME=\") }) {\n process.env.append(\"HOME=\\(parsedUser.home)\")\n }\n\n // Defensive programming a tad, but ensure we have TERM set if\n // the client requested a pty.\n if process.terminal {\n let termEnv = \"TERM=\"\n if !process.env.contains(where: { $0.hasPrefix(termEnv) }) {\n process.env.append(\"TERM=xterm\")\n }\n }\n\n ociSpec.process = process\n }\n}\n"], ["/containerization/Sources/Containerization/ContainerManager.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport ContainerizationExtras\nimport Virtualization\nimport vmnet\n\n/// A manager for creating and running containers.\n/// Supports container networking options.\npublic struct ContainerManager: Sendable {\n public let imageStore: ImageStore\n private let vmm: VirtualMachineManager\n private let network: Network?\n\n private var containerRoot: URL {\n self.imageStore.path.appendingPathComponent(\"containers\")\n }\n\n /// A network that can allocate and release interfaces for use with containers.\n public protocol Network: Sendable {\n func create(_ id: String) throws -> Interface?\n func release(_ id: String) throws\n }\n\n /// A network backed by vmnet on macOS.\n @available(macOS 26.0, *)\n public struct VmnetNetwork: Network {\n private let allocator: Allocator\n nonisolated(unsafe) private let reference: vmnet_network_ref\n\n /// The IPv4 subnet of this network.\n public let subnet: CIDRAddress\n\n /// The gateway address of this network.\n public var gateway: IPv4Address {\n subnet.gateway\n }\n\n struct Allocator: Sendable {\n private let addressAllocator: any AddressAllocator\n private let cidr: CIDRAddress\n private var allocations: [String: UInt32]\n\n init(cidr: CIDRAddress) throws {\n self.cidr = cidr\n self.allocations = .init()\n let size = Int(cidr.upper.value - cidr.lower.value - 3)\n self.addressAllocator = try UInt32.rotatingAllocator(\n lower: cidr.lower.value + 2,\n size: UInt32(size)\n )\n }\n\n func allocate(_ id: String) throws -> String {\n if allocations[id] != nil {\n throw ContainerizationError(.exists, message: \"allocation with id \\(id) already exists\")\n }\n let index = try addressAllocator.allocate()\n let ip = IPv4Address(fromValue: index)\n return try CIDRAddress(ip, prefixLength: cidr.prefixLength).description\n }\n\n func release(_ id: String) throws {\n if let index = self.allocations[id] {\n try addressAllocator.release(index)\n }\n }\n }\n\n /// A network interface supporting the vmnet_network_ref.\n public struct Interface: Containerization.Interface, VZInterface, Sendable {\n public let address: String\n public let gateway: String?\n public let macAddress: String?\n\n nonisolated(unsafe) private let reference: vmnet_network_ref\n\n public init(\n reference: vmnet_network_ref,\n address: String,\n gateway: String,\n macAddress: String? = nil\n ) {\n self.address = address\n self.gateway = gateway\n self.macAddress = macAddress\n self.reference = reference\n }\n\n /// Returns the underlying `VZVirtioNetworkDeviceConfiguration`.\n public func device() throws -> VZVirtioNetworkDeviceConfiguration {\n let config = VZVirtioNetworkDeviceConfiguration()\n if let macAddress = self.macAddress {\n guard let mac = VZMACAddress(string: macAddress) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid mac address \\(macAddress)\")\n }\n config.macAddress = mac\n }\n config.attachment = VZVmnetNetworkDeviceAttachment(network: self.reference)\n return config\n }\n }\n\n /// Creates a new network.\n /// - Parameter subnet: The subnet to use for this network.\n public init(subnet: String? = nil) throws {\n var status: vmnet_return_t = .VMNET_FAILURE\n guard let config = vmnet_network_configuration_create(.VMNET_SHARED_MODE, &status) else {\n throw ContainerizationError(.unsupported, message: \"failed to create vmnet config with status \\(status)\")\n }\n\n vmnet_network_configuration_disable_dhcp(config)\n\n if let subnet {\n try Self.configureSubnet(config, subnet: try CIDRAddress(subnet))\n }\n\n guard let ref = vmnet_network_create(config, &status), status == .VMNET_SUCCESS else {\n throw ContainerizationError(.unsupported, message: \"failed to create vmnet network with status \\(status)\")\n }\n\n let cidr = try Self.getSubnet(ref)\n\n self.allocator = try .init(cidr: cidr)\n self.subnet = cidr\n self.reference = ref\n }\n\n /// Returns a new interface for use with a container.\n /// - Parameter id: The container ID.\n public func create(_ id: String) throws -> Containerization.Interface? {\n let address = try allocator.allocate(id)\n return Self.Interface(\n reference: self.reference,\n address: address,\n gateway: self.gateway.description,\n )\n }\n\n /// Performs cleanup of an interface.\n /// - Parameter id: The container ID.\n public func release(_ id: String) throws {\n try allocator.release(id)\n }\n\n private static func getSubnet(_ ref: vmnet_network_ref) throws -> CIDRAddress {\n var subnet = in_addr()\n var mask = in_addr()\n vmnet_network_get_ipv4_subnet(ref, &subnet, &mask)\n\n let sa = UInt32(bigEndian: subnet.s_addr)\n let mv = UInt32(bigEndian: mask.s_addr)\n\n let lower = IPv4Address(fromValue: sa & mv)\n let upper = IPv4Address(fromValue: lower.value + ~mv)\n\n return try CIDRAddress(lower: lower, upper: upper)\n }\n\n private static func configureSubnet(_ config: vmnet_network_configuration_ref, subnet: CIDRAddress) throws {\n let gateway = subnet.gateway\n\n var ga = in_addr()\n inet_pton(AF_INET, gateway.description, &ga)\n\n let mask = IPv4Address(fromValue: subnet.prefixLength.prefixMask32)\n var ma = in_addr()\n inet_pton(AF_INET, mask.description, &ma)\n\n guard vmnet_network_configuration_set_ipv4_subnet(config, &ga, &ma) == .VMNET_SUCCESS else {\n throw ContainerizationError(.internalError, message: \"failed to set subnet \\(subnet) for network\")\n }\n }\n }\n\n /// Create a new manager with the provided kernel and initfs mount.\n public init(\n kernel: Kernel,\n initfs: Mount,\n network: Network? = nil\n ) throws {\n self.imageStore = ImageStore.default\n self.network = network\n try Self.createRootDirectory(path: self.imageStore.path)\n self.vmm = VZVirtualMachineManager(\n kernel: kernel,\n initialFilesystem: initfs,\n bootlog: self.imageStore.path.appendingPathComponent(\"bootlog.log\").absolutePath()\n )\n }\n\n /// Create a new manager with the provided kernel and image reference for the initfs.\n public init(\n kernel: Kernel,\n initfsReference: String,\n network: Network? = nil\n ) async throws {\n self.imageStore = ImageStore.default\n self.network = network\n try Self.createRootDirectory(path: self.imageStore.path)\n\n let initPath = self.imageStore.path.appendingPathComponent(\"initfs.ext4\")\n let initImage = try await self.imageStore.getInitImage(reference: initfsReference)\n let initfs = try await {\n do {\n return try await initImage.initBlock(at: initPath, for: .linuxArm)\n } catch let err as ContainerizationError {\n guard err.code == .exists else {\n throw err\n }\n return .block(\n format: \"ext4\",\n source: initPath.absolutePath(),\n destination: \"/\",\n options: [\"ro\"]\n )\n }\n }()\n\n self.vmm = VZVirtualMachineManager(\n kernel: kernel,\n initialFilesystem: initfs,\n bootlog: self.imageStore.path.appendingPathComponent(\"bootlog.log\").absolutePath()\n )\n }\n\n /// Create a new manager with the provided vmm and network.\n public init(\n vmm: any VirtualMachineManager,\n network: Network? = nil\n ) throws {\n self.imageStore = ImageStore.default\n try Self.createRootDirectory(path: self.imageStore.path)\n self.network = network\n self.vmm = vmm\n }\n\n private static func createRootDirectory(path: URL) throws {\n try FileManager.default.createDirectory(\n at: path.appendingPathComponent(\"containers\"),\n withIntermediateDirectories: true\n )\n }\n\n /// Returns a new container from the provided image reference.\n /// - Parameters:\n /// - id: The container ID.\n /// - reference: The image reference.\n /// - rootfsSizeInBytes: The size of the root filesystem in bytes. Defaults to 8 GiB.\n public func create(\n _ id: String,\n reference: String,\n rootfsSizeInBytes: UInt64 = 8.gib(),\n configuration: (inout LinuxContainer.Configuration) throws -> Void\n ) async throws -> LinuxContainer {\n let image = try await imageStore.get(reference: reference, pull: true)\n return try await create(\n id,\n image: image,\n rootfsSizeInBytes: rootfsSizeInBytes,\n configuration: configuration\n )\n }\n\n /// Returns a new container from the provided image.\n /// - Parameters:\n /// - id: The container ID.\n /// - image: The image.\n /// - rootfsSizeInBytes: The size of the root filesystem in bytes. Defaults to 8 GiB.\n public func create(\n _ id: String,\n image: Image,\n rootfsSizeInBytes: UInt64 = 8.gib(),\n configuration: (inout LinuxContainer.Configuration) throws -> Void\n ) async throws -> LinuxContainer {\n let path = try createContainerRoot(id)\n\n let rootfs = try await unpack(\n image: image,\n destination: path.appendingPathComponent(\"rootfs.ext4\"),\n size: rootfsSizeInBytes\n )\n return try await create(\n id,\n image: image,\n rootfs: rootfs,\n configuration: configuration\n )\n }\n\n /// Returns a new container from the provided image and root filesystem mount.\n /// - Parameters:\n /// - id: The container ID.\n /// - image: The image.\n /// - rootfs: The root filesystem mount pointing to an existing block file.\n public func create(\n _ id: String,\n image: Image,\n rootfs: Mount,\n configuration: (inout LinuxContainer.Configuration) throws -> Void\n ) async throws -> LinuxContainer {\n let imageConfig = try await image.config(for: .current).config\n return try LinuxContainer(\n id,\n rootfs: rootfs,\n vmm: self.vmm\n ) { config in\n if let imageConfig {\n config.process = .init(from: imageConfig)\n }\n if let interface = try self.network?.create(id) {\n config.interfaces = [interface]\n config.dns = .init(nameservers: [interface.gateway!])\n }\n try configuration(&config)\n }\n }\n\n /// Returns an existing container from the provided image and root filesystem mount.\n /// - Parameters:\n /// - id: The container ID.\n /// - image: The image.\n public func get(\n _ id: String,\n image: Image,\n ) async throws -> LinuxContainer {\n let path = containerRoot.appendingPathComponent(id)\n guard FileManager.default.fileExists(atPath: path.absolutePath()) else {\n throw ContainerizationError(.notFound, message: \"\\(id) does not exist\")\n }\n\n let rootfs: Mount = .block(\n format: \"ext4\",\n source: path.appendingPathComponent(\"rootfs.ext4\").absolutePath(),\n destination: \"/\",\n options: []\n )\n\n let imageConfig = try await image.config(for: .current).config\n return try LinuxContainer(\n id,\n rootfs: rootfs,\n vmm: self.vmm\n ) { config in\n if let imageConfig {\n config.process = .init(from: imageConfig)\n }\n if let interface = try self.network?.create(id) {\n config.interfaces = [interface]\n config.dns = .init(nameservers: [interface.gateway!])\n }\n }\n }\n\n /// Performs the cleanup of a container.\n /// - Parameter id: The container ID.\n public func delete(_ id: String) throws {\n try self.network?.release(id)\n let path = containerRoot.appendingPathComponent(id)\n try FileManager.default.removeItem(at: path)\n }\n\n private func createContainerRoot(_ id: String) throws -> URL {\n let path = containerRoot.appendingPathComponent(id)\n try FileManager.default.createDirectory(at: path, withIntermediateDirectories: false)\n return path\n }\n\n private func unpack(image: Image, destination: URL, size: UInt64) async throws -> Mount {\n do {\n let unpacker = EXT4Unpacker(blockSizeInBytes: size)\n return try await unpacker.unpack(image, for: .current, at: destination)\n } catch let err as ContainerizationError {\n if err.code == .exists {\n return .block(\n format: \"ext4\",\n source: destination.absolutePath(),\n destination: \"/\",\n options: []\n )\n }\n throw err\n }\n }\n}\n\nextension CIDRAddress {\n /// The gateway address of the network.\n public var gateway: IPv4Address {\n IPv4Address(fromValue: self.lower.value + 1)\n }\n}\n\n@available(macOS 26.0, *)\nprivate struct SendableReference: Sendable {\n nonisolated(unsafe) private let reference: vmnet_network_ref\n}\n\n#endif\n"], ["/containerization/Sources/Containerization/Image/ImageStore/ImageStore+Import.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\nextension ImageStore {\n internal struct ImportOperation {\n static let decoder = JSONDecoder()\n\n let client: ContentClient\n let ingestDir: URL\n let contentStore: ContentStore\n let progress: ProgressHandler?\n let name: String\n\n init(name: String, contentStore: ContentStore, client: ContentClient, ingestDir: URL, progress: ProgressHandler? = nil) {\n self.client = client\n self.ingestDir = ingestDir\n self.contentStore = contentStore\n self.progress = progress\n self.name = name\n }\n\n /// Pull the required image layers for the provided descriptor and platform(s) into the given directory using the provided client. Returns a descriptor to the Index manifest.\n internal func `import`(root: Descriptor, matcher: (ContainerizationOCI.Platform) -> Bool) async throws -> Descriptor {\n var toProcess = [root]\n while !toProcess.isEmpty {\n // Count the total number of blobs and their size\n if let progress {\n var size: Int64 = 0\n for desc in toProcess {\n size += desc.size\n }\n await progress([\n ProgressEvent(event: \"add-total-size\", value: size),\n ProgressEvent(event: \"add-total-items\", value: toProcess.count),\n ])\n }\n\n try await self.fetchAll(toProcess)\n let children = try await self.walk(toProcess)\n let filtered = try filterPlatforms(matcher: matcher, children)\n toProcess = filtered.uniqued { $0.digest }\n }\n\n guard root.mediaType != MediaTypes.dockerManifestList && root.mediaType != MediaTypes.index else {\n return root\n }\n\n // Create an index for the root descriptor and write it to the content store\n let index = try await self.createIndex(for: root)\n // In cases where the root descriptor pointed to `MediaTypes.imageManifest`\n // Or `MediaTypes.dockerManifest`, it is required that we check the supported platform\n // matches the platforms we were asked to pull. This can be done only after we created\n // the Index.\n let supportedPlatforms = index.manifests.compactMap { $0.platform }\n guard supportedPlatforms.allSatisfy(matcher) else {\n throw ContainerizationError(.unsupported, message: \"Image \\(root.digest) does not support required platforms\")\n }\n let writer = try ContentWriter(for: self.ingestDir)\n let result = try writer.create(from: index)\n return Descriptor(\n mediaType: MediaTypes.index,\n digest: result.digest.digestString,\n size: Int64(result.size))\n }\n\n private func getManifestContent(descriptor: Descriptor) async throws -> T {\n do {\n if let content = try await self.contentStore.get(digest: descriptor.digest.trimmingDigestPrefix) {\n return try content.decode()\n }\n if let content = try? LocalContent(path: ingestDir.appending(path: descriptor.digest.trimmingDigestPrefix)) {\n return try content.decode()\n }\n return try await self.client.fetch(name: name, descriptor: descriptor)\n } catch {\n throw ContainerizationError(.internalError, message: \"Cannot fetch content with digest \\(descriptor.digest)\", cause: error)\n }\n }\n\n private func walk(_ descriptors: [Descriptor]) async throws -> [Descriptor] {\n var out: [Descriptor] = []\n for desc in descriptors {\n let mediaType = desc.mediaType\n switch mediaType {\n case MediaTypes.index, MediaTypes.dockerManifestList:\n let index: Index = try await self.getManifestContent(descriptor: desc)\n out.append(contentsOf: index.manifests)\n case MediaTypes.imageManifest, MediaTypes.dockerManifest:\n let manifest: Manifest = try await self.getManifestContent(descriptor: desc)\n out.append(manifest.config)\n out.append(contentsOf: manifest.layers)\n default:\n // TODO: Explicitly handle other content types\n continue\n }\n }\n return out\n }\n\n private func fetchAll(_ descriptors: [Descriptor]) async throws {\n try await withThrowingTaskGroup(of: Void.self) { group in\n var iterator = descriptors.makeIterator()\n for _ in 0..<8 {\n if let desc = iterator.next() {\n group.addTask {\n try await fetch(desc)\n }\n }\n }\n for try await _ in group {\n if let desc = iterator.next() {\n group.addTask {\n try await fetch(desc)\n }\n }\n }\n }\n }\n\n private func fetch(_ descriptor: Descriptor) async throws {\n if let found = try await self.contentStore.get(digest: descriptor.digest) {\n try FileManager.default.copyItem(at: found.path, to: ingestDir.appendingPathComponent(descriptor.digest.trimmingDigestPrefix))\n await progress?([\n // Count the size of the blob\n ProgressEvent(event: \"add-size\", value: descriptor.size),\n // Count the number of blobs\n ProgressEvent(event: \"add-items\", value: 1),\n ])\n return\n }\n\n if descriptor.size > 1.mib() {\n try await self.fetchBlob(descriptor)\n } else {\n try await self.fetchData(descriptor)\n }\n // Count the number of blobs\n await progress?([\n ProgressEvent(event: \"add-items\", value: 1)\n ])\n }\n\n private func fetchBlob(_ descriptor: Descriptor) async throws {\n let id = UUID().uuidString\n let fm = FileManager.default\n let tempFile = ingestDir.appendingPathComponent(id)\n let (_, digest) = try await client.fetchBlob(name: name, descriptor: descriptor, into: tempFile, progress: progress)\n guard digest.digestString == descriptor.digest else {\n throw ContainerizationError(.internalError, message: \"Digest mismatch expected \\(descriptor.digest), got \\(digest.digestString)\")\n }\n do {\n try fm.moveItem(at: tempFile, to: ingestDir.appendingPathComponent(digest.encoded))\n } catch let err as NSError {\n guard err.code == NSFileWriteFileExistsError else {\n throw err\n }\n try fm.removeItem(at: tempFile)\n }\n }\n\n @discardableResult\n private func fetchData(_ descriptor: Descriptor) async throws -> Data {\n let data = try await client.fetchData(name: name, descriptor: descriptor)\n let writer = try ContentWriter(for: ingestDir)\n let result = try writer.write(data)\n if let progress {\n let size = Int64(result.size)\n await progress([\n ProgressEvent(event: \"add-size\", value: size)\n ])\n }\n guard result.digest.digestString == descriptor.digest else {\n throw ContainerizationError(.internalError, message: \"Digest mismatch expected \\(descriptor.digest), got \\(result.digest.digestString)\")\n }\n return data\n }\n\n private func createIndex(for root: Descriptor) async throws -> Index {\n switch root.mediaType {\n case MediaTypes.index, MediaTypes.dockerManifestList:\n return try await self.getManifestContent(descriptor: root)\n case MediaTypes.imageManifest, MediaTypes.dockerManifest:\n let supportedPlatforms = try await getSupportedPlatforms(for: root)\n guard supportedPlatforms.count == 1 else {\n throw ContainerizationError(\n .internalError,\n message:\n \"Descriptor \\(root.mediaType) with digest \\(root.digest) does not list any supported platform or supports more than one platform. Supported platforms = \\(supportedPlatforms)\"\n )\n }\n let platform = supportedPlatforms.first!\n var root = root\n root.platform = platform\n let index = ContainerizationOCI.Index(\n schemaVersion: 2, manifests: [root],\n annotations: [\n // indicate that this is a synthesized index which is not directly user facing\n AnnotationKeys.containerizationIndexIndirect: \"true\"\n ])\n return index\n default:\n throw ContainerizationError(.internalError, message: \"Failed to create index for descriptor \\(root.digest), media type \\(root.mediaType)\")\n }\n }\n\n private func getSupportedPlatforms(for root: Descriptor) async throws -> [ContainerizationOCI.Platform] {\n var supportedPlatforms: [ContainerizationOCI.Platform] = []\n var toProcess = [root]\n while !toProcess.isEmpty {\n let children = try await self.walk(toProcess)\n for child in children {\n if let p = child.platform {\n supportedPlatforms.append(p)\n continue\n }\n switch child.mediaType {\n case MediaTypes.imageConfig, MediaTypes.dockerImageConfig:\n let config: ContainerizationOCI.Image = try await self.getManifestContent(descriptor: child)\n let p = ContainerizationOCI.Platform(\n arch: config.architecture, os: config.os, osFeatures: config.osFeatures, variant: config.variant\n )\n supportedPlatforms.append(p)\n default:\n continue\n }\n }\n toProcess = children\n }\n return supportedPlatforms\n }\n\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Socket/Socket.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Synchronization\n\n#if canImport(Musl)\nimport Musl\n#elseif canImport(Glibc)\nimport Glibc\n#elseif canImport(Darwin)\nimport Darwin\n#else\n#error(\"Socket not supported on this platform.\")\n#endif\n\n#if !os(Windows)\nlet sysFchmod = fchmod\nlet sysRead = read\nlet sysUnlink = unlink\nlet sysSend = send\nlet sysClose = close\nlet sysShutdown = shutdown\nlet sysBind = bind\nlet sysSocket = socket\nlet sysSetsockopt = setsockopt\nlet sysGetsockopt = getsockopt\nlet sysListen = listen\nlet sysAccept = accept\nlet sysConnect = connect\nlet sysIoctl: @convention(c) (CInt, CUnsignedLong, UnsafeMutableRawPointer) -> CInt = ioctl\n#endif\n\n/// Thread-safe socket wrapper.\npublic final class Socket: Sendable {\n public enum TimeoutOption {\n case send\n case receive\n }\n\n public enum ShutdownOption {\n case read\n case write\n case readWrite\n }\n\n private enum SocketState {\n case created\n case connected\n case listening\n }\n\n private struct State {\n let socketState: SocketState\n let handle: FileHandle?\n let type: SocketType\n let acceptSource: DispatchSourceRead?\n }\n\n private let _closeOnDeinit: Bool\n private let _queue: DispatchQueue\n\n private let state: Mutex\n\n public var fileDescriptor: Int32 {\n guard let handle = state.withLock({ $0.handle }) else {\n return -1\n }\n return handle.fileDescriptor\n }\n\n public convenience init(type: SocketType, closeOnDeinit: Bool = true) throws {\n let sockFD = sysSocket(type.domain, type.type, 0)\n if sockFD < 0 {\n throw SocketError.withErrno(\"failed to create socket: \\(sockFD)\", errno: errno)\n }\n self.init(fd: sockFD, type: type, closeOnDeinit: closeOnDeinit)\n }\n\n init(fd: Int32, type: SocketType, closeOnDeinit: Bool) {\n _queue = DispatchQueue(label: \"com.apple.containerization.socket\")\n _closeOnDeinit = closeOnDeinit\n let state = State(\n socketState: .created,\n handle: FileHandle(fileDescriptor: fd, closeOnDealloc: false),\n type: type,\n acceptSource: nil\n )\n self.state = Mutex(state)\n }\n\n deinit {\n if _closeOnDeinit {\n try? close()\n }\n }\n}\n\nextension Socket {\n static func errnoToError(msg: String) -> SocketError {\n SocketError.withErrno(\"\\(msg) (\\(_errnoString(errno)))\", errno: errno)\n }\n\n public func connect() throws {\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n guard state.withLock({ $0.socketState }) == .created else {\n throw SocketError.invalidOperationOnSocket(\"connect\")\n }\n\n var res: Int32 = 0\n try state.withLock {\n try $0.type.withSockAddr { (ptr, length) in\n res = Syscall.retrying {\n sysConnect(handle.fileDescriptor, ptr, length)\n }\n }\n }\n if res == -1 {\n throw Socket.errnoToError(msg: \"could not connect to socket \\(state.withLock { $0.type })\")\n }\n state.withLock {\n $0 = State(\n socketState: .connected,\n handle: handle,\n type: $0.type,\n acceptSource: $0.acceptSource\n )\n }\n }\n\n public func listen() throws {\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n guard state.withLock({ $0.socketState }) == .created else {\n throw SocketError.invalidOperationOnSocket(\"listen\")\n }\n\n try state.withLock { try $0.type.beforeBind(fd: handle.fileDescriptor) }\n\n var rc: Int32 = 0\n try state.withLock {\n try $0.type.withSockAddr { (ptr, length) in\n rc = sysBind(handle.fileDescriptor, ptr, length)\n }\n }\n if rc < 0 {\n throw Socket.errnoToError(msg: \"could not bind to \\(state.withLock { $0.type })\")\n }\n\n try state.withLock { try $0.type.beforeListen(fd: handle.fileDescriptor) }\n if sysListen(handle.fileDescriptor, SOMAXCONN) < 0 {\n throw Socket.errnoToError(msg: \"listen failed on \\(state.withLock { $0.type })\")\n }\n state.withLock {\n $0 = State(\n socketState: .listening,\n handle: handle,\n type: $0.type,\n acceptSource: $0.acceptSource\n )\n }\n }\n\n public func close() throws {\n // Already closed.\n guard let handle = state.withLock({ $0.handle }) else {\n return\n }\n if let acceptSource = state.withLock({ $0.acceptSource }) {\n acceptSource.cancel()\n }\n try handle.close()\n state.withLock {\n $0 = State(\n socketState: $0.socketState,\n handle: nil,\n type: $0.type,\n acceptSource: nil\n )\n }\n }\n\n public func write(data: any DataProtocol) throws -> Int {\n guard state.withLock({ $0.socketState }) == .connected else {\n throw SocketError.invalidOperationOnSocket(\"write\")\n }\n\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n if data.isEmpty {\n return 0\n }\n\n try handle.write(contentsOf: data)\n return data.count\n }\n\n public func acceptStream(closeOnDeinit: Bool = true) throws -> AsyncThrowingStream {\n guard state.withLock({ $0.socketState }) == .listening else {\n throw SocketError.invalidOperationOnSocket(\"accept\")\n }\n\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n guard state.withLock({ $0.acceptSource }) == nil else {\n throw SocketError.acceptStreamExists\n }\n\n let source = state.withLock {\n let source = DispatchSource.makeReadSource(\n fileDescriptor: handle.fileDescriptor,\n queue: _queue\n )\n $0 = State(\n socketState: $0.socketState,\n handle: handle,\n type: $0.type,\n acceptSource: source\n )\n return source\n }\n\n return AsyncThrowingStream { cont in\n source.setCancelHandler {\n cont.finish()\n }\n source.setEventHandler(handler: {\n if source.data == 0 {\n source.cancel()\n return\n }\n\n do {\n let connection = try self.accept(closeOnDeinit: closeOnDeinit)\n cont.yield(connection)\n } catch SocketError.closed {\n source.cancel()\n } catch {\n cont.yield(with: .failure(error))\n source.cancel()\n }\n })\n source.activate()\n }\n }\n\n public func accept(closeOnDeinit: Bool = true) throws -> Socket {\n guard state.withLock({ $0.socketState }) == .listening else {\n throw SocketError.invalidOperationOnSocket(\"accept\")\n }\n\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n let (clientFD, socketType) = try state.withLock { try $0.type.accept(fd: handle.fileDescriptor) }\n return Socket(\n fd: clientFD,\n type: socketType,\n closeOnDeinit: closeOnDeinit\n )\n }\n\n public func read(buffer: inout Data) throws -> Int {\n guard state.withLock({ $0.socketState }) == .connected else {\n throw SocketError.invalidOperationOnSocket(\"read\")\n }\n\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n var bytesRead = 0\n let bufferSize = buffer.count\n try buffer.withUnsafeMutableBytes { pointer in\n guard let baseAddress = pointer.baseAddress else {\n throw SocketError.missingBaseAddress\n }\n\n bytesRead = Syscall.retrying {\n sysRead(handle.fileDescriptor, baseAddress, bufferSize)\n }\n if bytesRead < 0 {\n throw Socket.errnoToError(msg: \"Error reading from connection\")\n } else if bytesRead == 0 {\n throw SocketError.closed\n }\n }\n return bytesRead\n }\n\n public func shutdown(how: ShutdownOption) throws {\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n var howOpt: Int32 = 0\n switch how {\n case .read:\n howOpt = Int32(SHUT_RD)\n case .write:\n howOpt = Int32(SHUT_WR)\n case .readWrite:\n howOpt = Int32(SHUT_RDWR)\n }\n\n if sysShutdown(handle.fileDescriptor, howOpt) < 0 {\n throw Socket.errnoToError(msg: \"shutdown failed\")\n }\n }\n\n public func setSockOpt(sockOpt: Int32 = 0, ptr: UnsafeRawPointer, stride: UInt32) throws {\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n if setsockopt(handle.fileDescriptor, SOL_SOCKET, sockOpt, ptr, stride) < 0 {\n throw Socket.errnoToError(msg: \"failed to set sockopt\")\n }\n }\n\n public func setTimeout(option: TimeoutOption, seconds: Int) throws {\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n var sockOpt: Int32 = 0\n switch option {\n case .receive:\n sockOpt = SO_RCVTIMEO\n case .send:\n sockOpt = SO_SNDTIMEO\n }\n\n var timer = timeval()\n timer.tv_sec = seconds\n timer.tv_usec = 0\n\n if setsockopt(\n handle.fileDescriptor,\n SOL_SOCKET,\n sockOpt,\n &timer,\n socklen_t(MemoryLayout.size)\n ) < 0 {\n throw Socket.errnoToError(msg: \"failed to set read timeout\")\n }\n }\n\n static func _errnoString(_ err: Int32?) -> String {\n String(validatingCString: strerror(errno)) ?? \"error: \\(errno)\"\n }\n}\n\npublic enum SocketError: Error, Equatable, CustomStringConvertible {\n case closed\n case acceptStreamExists\n case invalidOperationOnSocket(String)\n case missingBaseAddress\n case withErrno(_ msg: String, errno: Int32)\n\n public var description: String {\n switch self {\n case .closed:\n return \"socket: closed\"\n case .acceptStreamExists:\n return \"accept stream already exists\"\n case .invalidOperationOnSocket(let operation):\n return \"socket: invalid operation on socket '\\(operation)'\"\n case .missingBaseAddress:\n return \"socket: missing base address\"\n case .withErrno(let msg, _):\n return \"socket: error \\(msg)\"\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/ArchiveWriter.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CArchive\nimport Foundation\n\n/// A class responsible for writing archives in various formats.\npublic final class ArchiveWriter {\n var underlying: OpaquePointer!\n var delegate: FileArchiveWriterDelegate?\n\n /// Initialize a new `ArchiveWriter` with the given configuration.\n /// This method attempts to initialize an empty archive in memory, failing which it throws a `unableToCreateArchive` error.\n public init(configuration: ArchiveWriterConfiguration) throws {\n // because for some bizarre reason, UTF8 paths won't work unless this process explicitly sets a locale like en_US.UTF-8\n try Self.attemptSetLocales(locales: configuration.locales)\n\n guard let underlying = archive_write_new() else { throw ArchiveError.unableToCreateArchive }\n self.underlying = underlying\n\n try setFormat(configuration.format)\n try addFilter(configuration.filter)\n try setOptions(configuration.options)\n }\n\n /// Initialize a new `ArchiveWriter` with the given configuration and specified delegate.\n private convenience init(configuration: ArchiveWriterConfiguration, delegate: FileArchiveWriterDelegate) throws {\n try self.init(configuration: configuration)\n self.delegate = delegate\n try self.open()\n }\n\n private convenience init(configuration: ArchiveWriterConfiguration, file: URL) throws {\n try self.init(configuration: configuration, delegate: FileArchiveWriterDelegate(url: file))\n }\n\n /// Initialize a new `ArchiveWriter` for writing into the specified file with the given configuration options.\n public convenience init(format: Format, filter: Filter, options: [Options] = [], file: URL) throws {\n try self.init(\n configuration: .init(format: format, filter: filter), delegate: FileArchiveWriterDelegate(url: file))\n }\n\n /// Opens the given file for writing data into\n public func open(file: URL) throws {\n guard let underlying = underlying else { throw ArchiveError.noUnderlyingArchive }\n let res = archive_write_open_filename(underlying, file.path)\n try wrap(res, ArchiveError.unableToOpenArchive, underlying: underlying)\n }\n\n /// Opens the given fd for writing data into\n public func open(fileDescriptor: Int32) throws {\n guard let underlying = underlying else { throw ArchiveError.noUnderlyingArchive }\n let res = archive_write_open_fd(underlying, fileDescriptor)\n try wrap(res, ArchiveError.unableToOpenArchive, underlying: underlying)\n }\n\n /// Performs any necessary finalizations on the archive and releases resources.\n public func finishEncoding() throws {\n if let u = underlying {\n let r = archive_free(u)\n do {\n try wrap(r, ArchiveError.unableToCloseArchive, underlying: underlying)\n underlying = nil\n } catch {\n underlying = nil\n throw error\n }\n }\n }\n\n deinit {\n if let u = underlying {\n archive_free(u)\n underlying = nil\n }\n }\n\n private static func attemptSetLocales(locales: [String]) throws {\n for locale in locales {\n if setlocale(LC_ALL, locale) != nil {\n return\n }\n }\n throw ArchiveError.failedToSetLocale(locales: locales)\n }\n}\n\nextension ArchiveWriter {\n fileprivate func open() throws {\n guard let underlying = underlying else { throw ArchiveError.noUnderlyingArchive }\n // TODO: to be or not to be retained, that is the question\n let pointerToSelf = Unmanaged.passUnretained(self).toOpaque()\n\n let res = archive_write_open2(\n underlying,\n pointerToSelf,\n /// The open callback is invoked by archive_write_open(). It should return ARCHIVE_OK if the underlying file or data source is successfully opened. If the open fails, it should call archive_set_error() to register an error code and message and return ARCHIVE_FATAL. Please note that\n /// if open fails, close is not called and resources must be freed inside the open callback or with the free callback.\n { underlying, pointerToSelf in\n do {\n guard let pointerToSelf = pointerToSelf else {\n throw ArchiveError.noArchiveInCallback\n }\n let archive: ArchiveWriter = Unmanaged.fromOpaque(pointerToSelf).takeUnretainedValue()\n guard let delegate = archive.delegate else {\n throw ArchiveError.noDelegateConfigured\n }\n try delegate.open(archive: archive)\n return ARCHIVE_OK\n } catch {\n archive_set_error_wrapper(underlying, ARCHIVE_FATAL, \"\\(error)\")\n return ARCHIVE_FATAL\n }\n },\n /// The write callback is invoked whenever the library needs to write raw bytes to the archive. For correct blocking, each call to the write callback function should translate into a single write(2) system call. This is especially critical when writing archives to tape drives. On\n /// success, the write callback should return the number of bytes actually written. On error, the callback should invoke archive_set_error() to register an error code and message and return -1.\n { underlying, pointerToSelf, dataPointer, count in\n do {\n guard let pointerToSelf = pointerToSelf else {\n throw ArchiveError.noArchiveInCallback\n }\n let archive: ArchiveWriter = Unmanaged.fromOpaque(pointerToSelf).takeUnretainedValue()\n guard let delegate = archive.delegate else {\n throw ArchiveError.noDelegateConfigured\n }\n return try delegate.write(\n archive: archive, buffer: UnsafeRawBufferPointer(start: dataPointer, count: count))\n } catch {\n archive_set_error_wrapper(underlying, ARCHIVE_FATAL, \"\\(error)\")\n return -1\n }\n },\n /// The close callback is invoked by archive_close when the archive processing is complete. If the open callback fails, the close callback is not invoked. The callback should return ARCHIVE_OK on success. On failure, the callback should invoke archive_set_error() to register an\n /// error code and message and return\n { underlying, pointerToSelf in\n do {\n guard let pointerToSelf = pointerToSelf else {\n throw ArchiveError.noArchiveInCallback\n }\n let archive: ArchiveWriter = Unmanaged.fromOpaque(pointerToSelf).takeUnretainedValue()\n guard let delegate = archive.delegate else {\n throw ArchiveError.noDelegateConfigured\n }\n try delegate.close(archive: archive)\n return ARCHIVE_OK\n } catch {\n archive_set_error_wrapper(underlying, ARCHIVE_FATAL, \"\\(error)\")\n return ARCHIVE_FATAL\n }\n },\n /// The free callback is always invoked on archive_free. The return code of this callback is not processed.\n { underlying, pointerToSelf in\n do {\n guard let pointerToSelf = pointerToSelf else {\n throw ArchiveError.noArchiveInCallback\n }\n let archive: ArchiveWriter = Unmanaged.fromOpaque(pointerToSelf).takeUnretainedValue()\n guard let delegate = archive.delegate else {\n throw ArchiveError.noDelegateConfigured\n }\n delegate.free(archive: archive)\n\n // TODO: should we balance the Unmanaged refcount here? Need to test for leaks.\n return ARCHIVE_OK\n } catch {\n archive_set_error_wrapper(underlying, ARCHIVE_FATAL, \"\\(error)\")\n return ARCHIVE_FATAL\n }\n }\n )\n\n try wrap(res, ArchiveError.unableToOpenArchive, underlying: underlying)\n }\n}\n\npublic class ArchiveWriterTransaction {\n private let writer: ArchiveWriter\n\n fileprivate init(writer: ArchiveWriter) {\n self.writer = writer\n }\n\n public func writeHeader(entry: WriteEntry) throws {\n try writer.writeHeader(entry: entry)\n }\n\n public func writeChunk(data: UnsafeRawBufferPointer) throws {\n try writer.writeData(data: data)\n }\n\n public func finish() throws {\n try writer.finishEntry()\n }\n}\n\nextension ArchiveWriter {\n public func makeTransactionWriter() -> ArchiveWriterTransaction {\n ArchiveWriterTransaction(writer: self)\n }\n\n /// Create a new entry in the archive with the given properties.\n /// - Parameters:\n /// - entry: A `WriteEntry` object describing the metadata of the entry to be created\n /// (e.g., name, modification date, permissions).\n /// - data: The `Data` object containing the content for the new entry.\n public func writeEntry(entry: WriteEntry, data: Data) throws {\n try data.withUnsafeBytes { bytes in\n try writeEntry(entry: entry, data: bytes)\n }\n }\n\n /// Creates a new entry in the archive with the given properties.\n ///\n /// This method performs the following:\n /// 1. Writes the archive header using the provided `WriteEntry` metadata.\n /// 2. Writes the content from the `UnsafeRawBufferPointer` into the archive.\n /// 3. Finalizes the entry in the archive.\n ///\n /// - Parameters:\n /// - entry: A `WriteEntry` object describing the metadata of the entry to be created\n /// (e.g., name, modification date, permissions, type).\n /// - data: An optional `UnsafeRawBufferPointer` containing the raw bytes for the new entry's\n /// content. Pass `nil` for entries that do not have content data (e.g., directories, symlinks).\n public func writeEntry(entry: WriteEntry, data: UnsafeRawBufferPointer?) throws {\n try writeHeader(entry: entry)\n if let data = data {\n try writeData(data: data)\n }\n try finishEntry()\n }\n\n fileprivate func writeHeader(entry: WriteEntry) throws {\n guard let underlying = self.underlying else { throw ArchiveError.noUnderlyingArchive }\n\n try wrap(\n archive_write_header(underlying, entry.underlying), ArchiveError.unableToWriteEntryHeader,\n underlying: underlying)\n }\n\n fileprivate func finishEntry() throws {\n guard let underlying = self.underlying else { throw ArchiveError.noUnderlyingArchive }\n\n archive_write_finish_entry(underlying)\n }\n\n fileprivate func writeData(data: UnsafeRawBufferPointer) throws {\n guard let underlying = self.underlying else { throw ArchiveError.noUnderlyingArchive }\n\n let result = archive_write_data(underlying, data.baseAddress, data.count)\n guard result >= 0 else {\n throw ArchiveError.unableToWriteData(result)\n }\n }\n}\n\nextension ArchiveWriter {\n /// Recursively archives the content of a directory. Regular files, symlinks and directories are added into the archive.\n /// Note: Symlinks are added to the archive if both the source and target for the symlink are both contained in the top level directory.\n public func archiveDirectory(_ dir: URL) throws {\n let fm = FileManager.default\n let resourceKeys = Set([\n .fileSizeKey, .fileResourceTypeKey,\n .creationDateKey, .contentAccessDateKey, .contentModificationDateKey, .fileSecurityKey,\n ])\n guard let directoryEnumerator = fm.enumerator(at: dir, includingPropertiesForKeys: Array(resourceKeys), options: .producesRelativePathURLs) else {\n throw POSIXError(.ENOTDIR)\n }\n for case let fileURL as URL in directoryEnumerator {\n var mode = mode_t()\n var uid = uid_t()\n var gid = gid_t()\n let resourceValues = try fileURL.resourceValues(forKeys: resourceKeys)\n guard let type = resourceValues.fileResourceType else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .fileResourceTypeKey)\n }\n let allowedTypes: [URLFileResourceType] = [.directory, .regular, .symbolicLink]\n guard allowedTypes.contains(type) else {\n continue\n }\n var size: Int64 = 0\n let entry = WriteEntry()\n if type == .regular {\n guard let _size = resourceValues.fileSize else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .fileSizeKey)\n }\n size = Int64(_size)\n } else if type == .symbolicLink {\n let target = fileURL.resolvingSymlinksInPath().absoluteString\n let root = dir.absoluteString\n guard target.hasPrefix(root) else {\n continue\n }\n let linkTarget = target.dropFirst(root.count + 1)\n entry.symlinkTarget = String(linkTarget)\n }\n\n guard let created = resourceValues.creationDate else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .creationDateKey)\n }\n guard let access = resourceValues.contentAccessDate else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .contentAccessDateKey)\n }\n guard let modified = resourceValues.contentModificationDate else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .contentModificationDateKey)\n }\n guard let perms = resourceValues.fileSecurity else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .fileSecurityKey)\n }\n CFFileSecurityGetMode(perms, &mode)\n CFFileSecurityGetOwner(perms, &uid)\n CFFileSecurityGetGroup(perms, &gid)\n entry.path = fileURL.relativePath\n entry.size = size\n entry.creationDate = created\n entry.modificationDate = modified\n entry.contentAccessDate = access\n entry.fileType = type\n entry.group = gid\n entry.owner = uid\n entry.permissions = mode\n if type == .regular {\n let p = dir.appending(path: fileURL.relativePath)\n let data = try Data(contentsOf: p, options: .uncached)\n try self.writeEntry(entry: entry, data: data)\n } else {\n try self.writeHeader(entry: entry)\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/RegistryClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport NIO\nimport NIOHTTP1\n\n#if os(macOS)\nimport Network\n#endif\n\n/// Data used to control retry behavior for `RegistryClient`.\npublic struct RetryOptions: Sendable {\n /// The maximum number of retries to attempt before failing.\n public var maxRetries: Int\n /// The retry interval in nanoseconds.\n public var retryInterval: UInt64\n /// A provided closure to handle if a given HTTP response should be\n /// retried.\n public var shouldRetry: (@Sendable (HTTPClientResponse) -> Bool)?\n\n public init(maxRetries: Int, retryInterval: UInt64, shouldRetry: (@Sendable (HTTPClientResponse) -> Bool)? = nil) {\n self.maxRetries = maxRetries\n self.retryInterval = retryInterval\n self.shouldRetry = shouldRetry\n }\n}\n\n/// A client for interacting with OCI compliant container registries.\npublic final class RegistryClient: ContentClient {\n private static let defaultRetryOptions = RetryOptions(\n maxRetries: 3,\n retryInterval: 1_000_000_000,\n shouldRetry: ({ response in\n response.status.code >= 500\n })\n )\n\n let client: HTTPClient\n let base: URLComponents\n let clientID: String\n let authentication: Authentication?\n let retryOptions: RetryOptions?\n let bufferSize: Int\n\n public convenience init(\n reference: String,\n insecure: Bool = false,\n auth: Authentication? = nil,\n logger: Logger? = nil\n ) throws {\n let ref = try Reference.parse(reference)\n guard let domain = ref.resolvedDomain else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid domain for image reference \\(reference)\")\n }\n let scheme = insecure ? \"http\" : \"https\"\n let _url = \"\\(scheme)://\\(domain)\"\n guard let url = URL(string: _url) else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot convert \\(_url) to URL\")\n }\n guard let host = url.host else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid host \\(domain)\")\n }\n let port = url.port\n self.init(\n host: host,\n scheme: scheme,\n port: port,\n authentication: auth,\n retryOptions: Self.defaultRetryOptions\n )\n }\n\n public init(\n host: String,\n scheme: String? = \"https\",\n port: Int? = nil,\n authentication: Authentication? = nil,\n clientID: String? = nil,\n retryOptions: RetryOptions? = nil,\n bufferSize: Int = Int(4.mib()),\n logger: Logger? = nil\n ) {\n var components = URLComponents()\n components.scheme = scheme\n components.host = host\n components.port = port\n\n self.base = components\n self.clientID = clientID ?? \"containerization-registry-client\"\n self.authentication = authentication\n self.retryOptions = retryOptions\n self.bufferSize = bufferSize\n var httpConfiguration = HTTPClient.Configuration()\n let proxyConfig: HTTPClient.Configuration.Proxy? = {\n let proxyEnv = ProcessInfo.processInfo.environment[\"HTTP_PROXY\"]\n guard let proxyEnv else {\n return nil\n }\n guard let url = URL(string: proxyEnv), let host = url.host(), let port = url.port else {\n return nil\n }\n return .server(host: host, port: port)\n }()\n httpConfiguration.proxy = proxyConfig\n if let logger {\n self.client = HTTPClient(eventLoopGroupProvider: .singleton, configuration: httpConfiguration, backgroundActivityLogger: logger)\n } else {\n self.client = HTTPClient(eventLoopGroupProvider: .singleton, configuration: httpConfiguration)\n }\n }\n\n deinit {\n _ = client.shutdown()\n }\n\n func host() -> String {\n base.host ?? \"\"\n }\n\n internal func request(\n components: URLComponents,\n method: HTTPMethod = .GET,\n bodyClosure: () throws -> HTTPClientRequest.Body? = { nil },\n headers: [(String, String)]? = nil,\n closure: (HTTPClientResponse) async throws -> T\n ) async throws -> T {\n guard let path = components.url?.absoluteString else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid url \\(components.path)\")\n }\n\n var request = HTTPClientRequest(url: path)\n request.method = method\n\n var currentToken: TokenResponse?\n let token: String? = try await {\n if let basicAuth = authentication {\n return try await basicAuth.token()\n }\n return nil\n }()\n\n if let token {\n request.headers.add(name: \"Authorization\", value: \"\\(token)\")\n }\n\n // Add any arbitrary headers\n headers?.forEach { (k, v) in request.headers.add(name: k, value: v) }\n var retryCount = 0\n var response: HTTPClientResponse?\n while true {\n request.body = try bodyClosure()\n do {\n let _response = try await client.execute(request, deadline: .distantFuture)\n response = _response\n if _response.status == .unauthorized || _response.status == .forbidden {\n let authHeader = _response.headers[TokenRequest.authenticateHeaderName]\n let tokenRequest: TokenRequest\n do {\n tokenRequest = try self.createTokenRequest(parsing: authHeader)\n } catch {\n // The server did not tell us how to authenticate our requests,\n // Or we do not support scheme the server is requesting for.\n // Throw the 401/403 to the caller, and let them decide how to proceed.\n throw RegistryClient.Error.invalidStatus(url: path, _response.status, reason: String(describing: error))\n }\n if let ct = currentToken, ct.isValid(scope: tokenRequest.scope) {\n break\n }\n\n do {\n let _currentToken = try await fetchToken(request: tokenRequest)\n guard let token = _currentToken.getToken() else {\n throw ContainerizationError(.internalError, message: \"Failed to fetch Bearer token\")\n }\n currentToken = _currentToken\n request.headers.replaceOrAdd(name: \"Authorization\", value: token)\n retryCount += 1\n } catch let err as RegistryClient.Error {\n guard case .invalidStatus(_, let status, _) = err else {\n throw err\n }\n if status == .unauthorized || status == .forbidden {\n throw RegistryClient.Error.invalidStatus(url: path, _response.status, reason: \"Access denied or wrong credentials\")\n }\n\n throw err\n }\n\n continue\n }\n guard let retryOptions = self.retryOptions else {\n break\n }\n guard retryCount < retryOptions.maxRetries else {\n break\n }\n guard let shouldRetry = retryOptions.shouldRetry, shouldRetry(_response) else {\n break\n }\n retryCount += 1\n try await Task.sleep(nanoseconds: retryOptions.retryInterval)\n continue\n } catch let err as RegistryClient.Error {\n throw err\n } catch {\n #if os(macOS)\n if let err = error as? NWError {\n if err.errorCode == kDNSServiceErr_NoSuchRecord {\n throw ContainerizationError(.internalError, message: \"No Such DNS Record \\(host())\")\n }\n }\n #endif\n guard let retryOptions = self.retryOptions, retryCount < retryOptions.maxRetries else {\n throw error\n }\n retryCount += 1\n try await Task.sleep(nanoseconds: retryOptions.retryInterval)\n }\n }\n guard let response else {\n throw ContainerizationError(.internalError, message: \"Invalid response\")\n }\n return try await closure(response)\n }\n\n internal func requestData(\n components: URLComponents,\n headers: [(String, String)]? = nil\n ) async throws -> Data {\n let bytes: ByteBuffer = try await requestBuffer(components: components, headers: headers)\n return Data(buffer: bytes)\n }\n\n internal func requestBuffer(\n components: URLComponents,\n headers: [(String, String)]? = nil\n ) async throws -> ByteBuffer {\n try await request(components: components, method: .GET, headers: headers) { response in\n guard response.status == .ok else {\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n\n return try await response.body.collect(upTo: self.bufferSize)\n }\n }\n\n internal func requestJSON(\n components: URLComponents,\n headers: [(String, String)]? = nil\n ) async throws -> T {\n let buffer = try await self.requestBuffer(components: components, headers: headers)\n return try JSONDecoder().decode(T.self, from: buffer)\n }\n\n /// A minimal endpoint, mounted at /v2/ will provide version support information based on its response statuses.\n /// See https://distribution.github.io/distribution/spec/api/#api-version-check\n public func ping() async throws {\n var components = base\n components.path = \"/v2/\"\n\n try await request(components: components) { response in\n guard response.status == .ok else {\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Formatter.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// swiftlint: disable discouraged_direct_init shorthand_operator syntactic_sugar\n\nimport ContainerizationOS\nimport Foundation\nimport SystemPackage\n\nextension EXT4 {\n /// The `EXT4.Formatter` class provides methods to format a block device with the ext4 filesystem.\n /// It allows customization of block size and maximum disk size.\n public class Formatter {\n private let blockSize: UInt32\n private var size: UInt64\n private let groupDescriptorSize: UInt32 = 32\n\n private var blocksPerGroup: UInt32 {\n blockSize * 8\n }\n\n private var maxInodesPerGroup: UInt32 {\n blockSize * 8 // limited by inode bitmap\n }\n\n private var groupsPerDescriptorBlock: UInt32 {\n blockSize / groupDescriptorSize\n }\n\n private var blockCount: UInt32 {\n ((size - 1) / blockSize) + 1\n }\n\n private var groupCount: UInt32 {\n (blockCount - 1) / blocksPerGroup + 1\n }\n\n private var groupDescriptorBlocks: UInt32 {\n ((groupCount - 1) / groupsPerDescriptorBlock + 1) * 32\n }\n\n /// Initializes an ext4 filesystem formatter.\n ///\n /// This constructor creates an instance of the ext4 formatter designed to format a block device\n /// with the ext4 filesystem. The formatter takes the path to the destination block device and\n /// the desired block size of the filesystem as parameters.\n ///\n /// - Parameters:\n /// - devicePath: The path to the block device where the ext4 filesystem will be created.\n /// - blockSize: The block size of the ext4 filesystem, specified in bytes. Common values are\n /// 4096 (4KB) or 1024 (1KB). Default is 4096 (4KB)\n /// - minDiskSize: The minimum disk size required for the formatted filesystem.\n ///\n /// - Note: This ext4 formatter is designed for creating block devices out of container images and does not support all the\n /// features and options available in the full ext4 filesystem implementation. It focuses\n /// on the core functionality required for formatting a block device with ext4.\n ///\n /// - Important: Ensure that the destination block device is accessible and has sufficient permissions\n /// for formatting. The formatting process will erase all existing data on the device.\n public init(_ devicePath: FilePath, blockSize: UInt32 = 4096, minDiskSize: UInt64 = 256.kib()) throws {\n /// The constructor performs the following steps:\n ///\n /// 1. Creates the first 10 inodes:\n /// - Inode 2 is reserved for the root directory ('/').\n /// - Inodes 1 and 3-10 are reserved for other special purposes.\n ///\n /// 2. Marks inode 11 as the first inode available for consumption by files, directories, sockets,\n /// FIFOs, etc.\n ///\n /// 3. Initializes a directory tree with the root directory pointing to inode 2.\n ///\n /// 4. Moves the file descriptor to the start of the block where file metadata and data can be\n /// written, which is located past the filesystem superblocks and group descriptor blocks.\n ///\n /// 5. Creates a \"/lost+found\" directory to satisfy the requirements of e2fsck (ext2/3/4 filesystem\n /// checker).\n\n if !FileManager.default.fileExists(atPath: devicePath.description) {\n FileManager.default.createFile(atPath: devicePath.description, contents: nil)\n }\n guard let fileHandle = FileHandle(forWritingTo: devicePath) else {\n throw Error.notFound(devicePath)\n }\n self.handle = fileHandle\n self.blockSize = blockSize\n self.size = minDiskSize\n // make this a 0 byte file\n guard ftruncate(self.handle.fileDescriptor, 0) == 0 else {\n throw Error.cannotTruncateFile(devicePath)\n }\n // make it a sparse file\n guard lseek(self.handle.fileDescriptor, off_t(self.size - 1), 0) == self.size - 1 else {\n throw Error.cannotCreateSparseFile(devicePath)\n }\n let zero: [UInt8] = [0]\n try self.handle.write(contentsOf: zero)\n // step #1\n self.inodes = [\n Ptr.allocate(capacity: 1), // defective block inode\n {\n let root = Inode.Root()\n let rootPtr = Ptr.allocate(capacity: 1)\n rootPtr.initialize(to: root)\n return rootPtr\n }(),\n ]\n // reserved inodes\n for _ in 2...allocate(capacity: 1))\n }\n // step #2\n self.tree = FileTree(EXT4.RootInode, \"/\")\n // skip past the superblock and block descriptor table\n try self.seek(block: self.groupDescriptorBlocks + 1)\n // lost+found directory is required for e2fsck to pass\n try self.create(path: FilePath(\"/lost+found\"), mode: Inode.Mode(.S_IFDIR, 0o700))\n }\n\n // Creates a hard link at the path specified by `link` that points to the same file or directory as the path specified by `target`.\n //\n // A hard link is a directory entry that points to the same inode as another directory entry. It allows multiple paths to refer to the same file on the file system.\n //\n // - `link`: The path at which to create the new hard link.\n // - `target`: The path of the existing file or directory to which the hard link should point.\n //\n // Throws an error if `target` path does not exist, or `target` is a directory.\n public func link(\n link: FilePath,\n target: FilePath\n ) throws {\n // ensure that target exists\n guard let targetPtr = self.tree.lookup(path: target) else {\n throw Error.notFound(target)\n }\n let targetNode = targetPtr.pointee\n let targetInodePtr = self.inodes[Int(targetNode.inode) - 1]\n var targetInode = targetInodePtr.pointee\n // ensure that target is not a directory since hardlinks cannot be\n // created to directories\n if targetInode.mode.isDir() {\n throw Error.cannotCreateHardlinksToDirTarget(link)\n }\n targetInode.linksCount += 1\n targetInodePtr.initialize(to: targetInode)\n let parentPath: FilePath = link.dir\n if self.tree.lookup(path: link) != nil {\n try self.unlink(path: link)\n }\n guard let parentTreeNodePtr = self.tree.lookup(path: parentPath) else {\n throw Error.notFound(parentPath)\n }\n let parentTreeNode = parentTreeNodePtr.pointee\n let parentInodePtr = self.inodes[Int(parentTreeNode.inode) - 1]\n let parentInode = parentInodePtr.pointee\n guard parentInode.linksCount < EXT4.MaxLinks else {\n throw Error.maximumLinksExceeded(parentPath)\n }\n let linkTreeNodePtr = Ptr.allocate(capacity: 1)\n let linkTreeNode = FileTree.FileTreeNode(\n inode: InodeNumber(2), // this field is ignored, using 2 so array operations dont panic\n name: link.base,\n parent: parentTreeNodePtr,\n children: [],\n blocks: nil,\n link: targetNode.inode\n )\n linkTreeNodePtr.initialize(to: linkTreeNode)\n parentTreeNode.children.append(linkTreeNodePtr)\n parentTreeNodePtr.initialize(to: parentTreeNode)\n }\n\n // Deletes the file or directory at the specified path from the filesystem.\n //\n // It performs the following actions\n // - set link count of the file's inode to 0\n // - recursively set link count to 0 for its children\n // - free the inode\n // - free data blocks\n // - remove directory entry\n //\n // - `path`: The `FilePath` specifying the path of the file or directory to delete.\n public func unlink(path: FilePath, directoryWhiteout: Bool = false) throws {\n guard let pathPtr = self.tree.lookup(path: path) else {\n // We are being asked to unlink something that does not exist. Ignore\n return\n }\n let pathNode = pathPtr.pointee\n let inodeNumber = Int(pathNode.inode) - 1\n let pathInodePtr = self.inodes[inodeNumber]\n var pathInode = pathInodePtr.pointee\n\n if directoryWhiteout && !pathInode.mode.isDir() {\n throw Error.notDirectory(path)\n }\n\n for childPtr in pathNode.children {\n try self.unlink(path: path.join(childPtr.pointee.name))\n }\n\n guard !directoryWhiteout else {\n return\n }\n\n if let parentNodePtr = self.tree.lookup(path: path.dir) {\n let parentNode = parentNodePtr.pointee\n let parentInodePtr = self.inodes[Int(parentNode.inode) - 1]\n var parentInode = parentInodePtr.pointee\n if pathInode.mode.isDir() {\n if parentInode.linksCount > 2 {\n parentInode.linksCount -= 1\n }\n }\n parentInodePtr.initialize(to: parentInode)\n parentNode.children.removeAll { childPtr in\n childPtr.pointee.name == path.base\n }\n parentNodePtr.initialize(to: parentNode)\n }\n\n if let hardlink = pathNode.link {\n // the file we are deleting is a hardlink, decrement the link count\n let linkedInodePtr = self.inodes[Int(hardlink - 1)]\n var linkedInode = linkedInodePtr.pointee\n if linkedInode.linksCount > 2 {\n linkedInode.linksCount -= 1\n linkedInodePtr.initialize(to: linkedInode)\n }\n }\n\n guard inodeNumber > FirstInode else {\n // Free the inodes and the blocks related to the inode only if its valid\n return\n }\n if let blocks = pathNode.blocks {\n if !(blocks.start == blocks.end) {\n self.deletedBlocks.append((start: blocks.start, end: blocks.end))\n }\n }\n for block in pathNode.additionalBlocks ?? [] {\n self.deletedBlocks.append((start: block.start, end: block.end))\n }\n let now = Date().fs()\n pathInode = Inode()\n pathInode.dtime = now.lo\n pathInodePtr.initialize(to: pathInode)\n }\n\n // Creates a file, directory, or symlink at the specified path, recursively creating parent directories if they don't already exist.\n //\n // - Parameters:\n // - path: The FilePath representing the path where the file, directory, or symlink should be created.\n // - link: An optional FilePath representing the target path for a symlink. If `nil`, a regular file or directory will be created. Preceding '/' should be omitted\n // - mode: The permissions to set for the created file, directory, or symlink.\n // - buf: An `InputStream` object providing the contents for the created file. Ignored when creating directories or symlinks.\n //\n // - Note:\n // - This function recursively creates parent directories if they don't already exist. The `uid` and `gid` of the created parent directories are set to the values of their parent's `uid` and `gid`.\n // - It is expected that the user sets the permissions explicitly later\n // - This function only supports creating files, directories, and symlinks. Attempting to create other types of file system objects will result in an error.\n // - In case of symlinks, the preceding '/' should be omitted\n //\n // - Example usage:\n // ```swift\n // let formatter = EXT4.Formatter(devicePath: \"ext4.img\")\n // // create a directory\n // try formatter.create(path: FilePath(\"/dir\"),\n // mode: EXT4.Inode.Mode(.S_IFDIR, 0o700))\n //\n // // create a file\n // let inputStream = InputStream(data: \"data\".data(using: .utf8)!)\n // inputStream.open()\n // try formatter.create(path: FilePath(\"/dir/file\"),\n // mode: EXT4.Inode.Mode(.S_IFREG, 0o755), buf: inputStream)\n // inputStream.close()\n //\n // // create a symlink\n // try formatter.create(path: FilePath(\"/symlink\"), link: \"/dir/file\",\n // mode: EXT4.Inode.Mode(.S_IFLNK, 0o700))\n // ```\n public func create(\n path: FilePath,\n link: FilePath? = nil, // to create symbolic links\n mode: UInt16,\n ts: FileTimestamps = FileTimestamps(),\n buf: InputStream? = nil,\n uid: UInt32? = nil,\n gid: UInt32? = nil,\n xattrs: [String: Data]? = nil,\n recursion: Bool = false\n ) throws {\n if let nodePtr = self.tree.lookup(path: path) {\n let node = nodePtr.pointee\n let inodePtr = self.inodes[Int(node.inode) - 1]\n let inode = inodePtr.pointee\n // Allowed replace\n // -----------------------------\n //\n // Original Type File Directory Symlink\n // ----------------------------------------------\n // File | ✔ | ✘ | ✔\n // Directory | ✘ | ✔ | ✔\n // Symlink | ✔ | ✘ | ✔\n if mode.isDir() {\n if !inode.mode.isDir() {\n guard inode.mode.isLink() else {\n throw Error.notDirectory(path)\n }\n }\n // mkdir -p\n if path.base == node.name {\n guard !recursion else {\n return\n }\n // create a new tree node to replace this one\n var inode = inode\n inode.mode = mode\n if let uid {\n inode.uid = uid.lo\n inode.uidHigh = uid.hi\n }\n if let gid {\n inode.gid = gid.lo\n inode.gidHigh = gid.hi\n }\n inodePtr.initialize(to: inode)\n return\n }\n } else if let _ = node.link { // ok to overwrite links\n try self.unlink(path: path)\n } else { // file can only be overwritten by another file\n if inode.mode.isDir() {\n guard mode.isLink() else { // unless it is a link, then it can be replaced by a dir\n throw Error.notFile(path)\n }\n }\n try self.unlink(path: path)\n }\n }\n // create all predecessors recursively\n let parentPath: FilePath = path.dir\n try self.create(path: parentPath, mode: Inode.Mode(.S_IFDIR, 0o755), recursion: true)\n guard let parentTreeNodePtr = self.tree.lookup(path: parentPath) else {\n throw Error.notFound(parentPath)\n }\n let parentTreeNode = parentTreeNodePtr.pointee\n let parentInodePtr = self.inodes[Int(parentTreeNode.inode) - 1]\n var parentInode = parentInodePtr.pointee\n guard parentInode.linksCount < EXT4.MaxLinks else {\n throw Error.maximumLinksExceeded(parentPath)\n }\n\n let childInodePtr = Ptr.allocate(capacity: 1)\n var childInode = Inode()\n var startBlock: UInt32 = 0\n var endBlock: UInt32 = 0\n defer { // update metadata\n childInodePtr.initialize(to: childInode)\n parentInodePtr.initialize(to: parentInode)\n self.inodes.append(childInodePtr)\n let childTreeNodePtr = Ptr.allocate(capacity: 1)\n let childTreeNode = FileTree.FileTreeNode(\n inode: InodeNumber(self.inodes.count),\n name: path.base,\n parent: parentTreeNodePtr,\n children: [],\n blocks: (startBlock, endBlock)\n )\n childTreeNodePtr.initialize(to: childTreeNode)\n parentTreeNode.children.append(childTreeNodePtr)\n parentTreeNodePtr.initialize(to: parentTreeNode)\n }\n childInode.mode = mode\n // uid,gid\n if let uid {\n childInode.uid = UInt16(uid & 0xffff)\n childInode.uidHigh = UInt16((uid >> 16) & 0xffff)\n } else {\n childInode.uid = parentInode.uid\n childInode.uidHigh = parentInode.uidHigh\n }\n if let gid {\n childInode.gid = UInt16(gid & 0xffff)\n childInode.gidHigh = UInt16((gid >> 16) & 0xffff)\n } else {\n childInode.gid = parentInode.gid\n childInode.gidHigh = parentInode.gidHigh\n }\n if let xattrs, !xattrs.isEmpty {\n var state = FileXattrsState(\n inode: UInt32(self.inodes.count), inodeXattrCapacity: EXT4.InodeExtraSize, blockCapacity: blockSize)\n try state.add(ExtendedAttribute(name: \"system.data\", value: []))\n for (s, d) in xattrs {\n let attribute = ExtendedAttribute(name: s, value: [UInt8](d))\n try state.add(attribute)\n }\n if !state.inlineAttributes.isEmpty {\n var buffer: [UInt8] = .init(repeating: 0, count: Int(EXT4.InodeExtraSize))\n try state.writeInlineAttributes(buffer: &buffer)\n childInode.inlineXattrs = (\n buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5], buffer[6], buffer[7],\n buffer[8],\n buffer[9],\n buffer[10], buffer[11], buffer[12], buffer[13], buffer[14], buffer[15], buffer[16], buffer[17],\n buffer[18],\n buffer[19],\n buffer[20], buffer[21], buffer[22], buffer[23], buffer[24], buffer[25], buffer[26], buffer[27],\n buffer[28],\n buffer[29],\n buffer[30], buffer[31], buffer[32], buffer[33], buffer[34], buffer[35], buffer[36], buffer[37],\n buffer[38],\n buffer[39],\n buffer[40], buffer[41], buffer[42], buffer[43], buffer[44], buffer[45], buffer[46], buffer[47],\n buffer[48],\n buffer[49],\n buffer[50], buffer[51], buffer[52], buffer[53], buffer[54], buffer[55], buffer[56], buffer[57],\n buffer[58],\n buffer[59],\n buffer[60], buffer[61], buffer[62], buffer[63], buffer[64], buffer[65], buffer[66], buffer[67],\n buffer[68],\n buffer[69],\n buffer[70], buffer[71], buffer[72], buffer[73], buffer[74], buffer[75], buffer[76], buffer[77],\n buffer[78],\n buffer[79],\n buffer[80], buffer[81], buffer[82], buffer[83], buffer[84], buffer[85], buffer[86], buffer[87],\n buffer[88],\n buffer[89],\n buffer[90], buffer[91], buffer[92], buffer[93], buffer[94], buffer[95]\n )\n childInode.flags |= InodeFlag.inlineData.rawValue\n }\n if !state.blockAttributes.isEmpty {\n var buffer: [UInt8] = .init(repeating: 0, count: Int(blockSize))\n try state.writeBlockAttributes(buffer: &buffer)\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n childInode.xattrBlockLow = self.currentBlock\n try self.handle.write(contentsOf: buffer)\n childInode.blocksLow += 1\n }\n }\n\n childInode.atime = ts.accessLo\n childInode.atimeExtra = ts.accessHi\n // ctime is the last time the inode was changed which is now\n childInode.ctime = ts.nowLo\n childInode.ctimeExtra = ts.nowHi\n childInode.mtime = ts.modificationLo\n childInode.mtimeExtra = ts.modificationHi\n childInode.crtime = ts.creationLo\n childInode.crtimeExtra = ts.creationHi\n childInode.linksCount = 1\n childInode.extraIsize = UInt16(EXT4.ExtraIsize)\n // flags\n childInode.flags = InodeFlag.hugeFile.rawValue\n // size check\n var size: UInt64 = 0\n // align with block boundary\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n // dir\n if childInode.mode.isDir() {\n childInode.linksCount += 1\n parentInode.linksCount += 1\n // to pass e2fsck, the convention is to sort children\n // before committing to disk. Therefore, we are deferring\n // writing dentries until commit() is called\n return\n }\n // symbolic link\n if let link {\n startBlock = self.currentBlock\n let linkPath = link.bytes\n if linkPath.count < 60 {\n size += UInt64(linkPath.count)\n var blockData: [UInt8] = .init(repeating: 0, count: 60)\n for i in 0...allocate(capacity: Int(self.blockSize))\n defer { tempBuf.deallocate() }\n while case let block = buf.read(tempBuf.underlying, maxLength: Int(self.blockSize)), block > 0 {\n size += UInt64(block)\n if size > EXT4.MaxFileSize {\n throw Error.fileTooBig(size)\n }\n let data = UnsafeRawBufferPointer(start: tempBuf.underlying, count: block)\n try withUnsafeLittleEndianBuffer(of: data) { b in\n try self.handle.write(contentsOf: b)\n }\n }\n }\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n endBlock = self.currentBlock\n childInode.sizeLow = size.lo\n childInode.sizeHigh = size.hi\n childInode = try self.writeExtents(childInode, (startBlock, endBlock))\n return\n }\n // FIFO, Socket and other types are not handled\n throw Error.unsupportedFiletype\n }\n\n public func setOwner(path: FilePath, uid: UInt16? = nil, gid: UInt16? = nil, recursive: Bool = false) throws {\n // ensure that target exists\n guard let pathPtr = self.tree.lookup(path: path) else {\n throw Error.notFound(path)\n }\n let pathNode = pathPtr.pointee\n let pathInodePtr = self.inodes[Int(pathNode.inode) - 1]\n var pathInode = pathInodePtr.pointee\n if let uid {\n pathInode.uid = uid\n }\n if let gid {\n pathInode.gid = gid\n }\n pathInodePtr.initialize(to: pathInode)\n if recursive {\n for childPtr in pathNode.children {\n let child = childPtr.pointee\n try self.setOwner(path: path.join(child.name), uid: uid, gid: gid, recursive: recursive)\n }\n }\n }\n\n // Completes the formatting of an ext4 filesystem after writing the necessary structures.\n //\n // This function is responsible for finalizing the formatting process of an ext4 filesystem\n // after the following structures have been written:\n // - Inode table: Contains information about each file and directory in the filesystem.\n // - Block bitmap: Tracks the allocation status of each block in the filesystem.\n // - Inode bitmap: Tracks the allocation status of each inode in the filesystem.\n // - Directory tree: Represents the hierarchical structure of directories and files.\n // - Group descriptors: Stores metadata about each block group in the filesystem.\n // - Superblock: Contains essential information about the filesystem's configuration.\n //\n // The function performs any necessary final steps to ensure the integrity and consistency\n // of the ext4 filesystem before it can be mounted and used.\n public func close() throws {\n var breathWiseChildTree: [(parent: Ptr?, child: Ptr)] = [\n (nil, self.tree.root)\n ]\n while !breathWiseChildTree.isEmpty {\n let (parent, child) = breathWiseChildTree.removeFirst()\n try self.commit(parent, child) // commit directories iteratively\n if child.pointee.link != nil {\n continue\n }\n breathWiseChildTree.append(contentsOf: child.pointee.children.map { (child, $0) })\n }\n let blockGroupSize = optimizeBlockGroupLayout(blocks: self.currentBlock, inodes: UInt32(self.inodes.count))\n let inodeTableOffset = try self.commitInodeTable(\n blockGroups: blockGroupSize.blockGroups,\n inodesPerGroup: blockGroupSize.inodesPerGroup\n )\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n // write bitmaps and group descriptors\n\n let bitmapOffset = self.currentBlock\n let bitmapSize: UInt32 = blockGroupSize.blockGroups * 2 // each group has two bitmaps - for inodes, and for blocks\n let dataSize: UInt32 = bitmapOffset + bitmapSize // last data block\n var diskSize = dataSize\n var minimumDiskSize = (blockGroupSize.blockGroups - 1) * self.blocksPerGroup + 1\n if blockGroupSize.blockGroups == 1 {\n minimumDiskSize = self.blocksPerGroup // at least 1 block group\n }\n if diskSize < minimumDiskSize { // for data + metadata\n diskSize = minimumDiskSize\n }\n if self.size < minimumDiskSize {\n self.size = UInt64(minimumDiskSize) * self.blockSize\n }\n // number of blocks needed for group descriptors\n let groupDescriptorBlockCount: UInt32 = (blockGroupSize.blockGroups - 1) / self.groupsPerDescriptorBlock + 1\n guard groupDescriptorBlockCount <= self.groupDescriptorBlocks else {\n throw Error.insufficientSpaceForGroupDescriptorBlocks\n }\n\n var totalBlocks: UInt32 = 0\n var totalInodes: UInt32 = 0\n let inodeTableSizePerGroup: UInt32 = blockGroupSize.inodesPerGroup * EXT4.InodeSize / self.blockSize\n var groupDescriptors: [GroupDescriptor] = []\n\n let minGroups = (((self.pos / UInt64(self.blockSize)) - 1) / UInt64(self.blocksPerGroup)) + 1\n if self.size < minGroups * blocksPerGroup * blockSize {\n self.size = UInt64(minGroups * blocksPerGroup * blockSize)\n let pos = self.pos\n guard lseek(self.handle.fileDescriptor, off_t(self.size - 1), 0) == self.size - 1 else {\n throw Error.cannotResizeFS(self.size)\n }\n let zero: [UInt8] = [0]\n try self.handle.write(contentsOf: zero)\n try self.handle.seek(toOffset: pos)\n }\n let totalGroups = (((self.size / UInt64(self.blockSize)) - 1) / UInt64(self.blocksPerGroup)) + 1\n\n // If the provided disk size is not aligned to a blockgroup boundary, it needs to\n // be expanded to the next blockgroup boundary.\n // Example:\n // Provided disk size: 2 GB + 100MB: 2148 MB\n // BlockSize: 4096\n // Blockgroup size: 32768 blocks: 128MB\n // Number of blocks: 549888\n // Number of blockgroups = 549888 / 32768 = 16.78125\n // Aligned disk size = 557056 blocks = 17 blockgroups: 2176 MB\n if self.size < totalGroups * blocksPerGroup * blockSize {\n self.size = UInt64(totalGroups * blocksPerGroup * blockSize)\n let pos = self.pos\n guard lseek(self.handle.fileDescriptor, off_t(self.size - 1), 0) == self.size - 1 else {\n throw Error.cannotResizeFS(self.size)\n }\n let zero: [UInt8] = [0]\n try self.handle.write(contentsOf: zero)\n try self.handle.seek(toOffset: pos)\n }\n for group in 0..> (j % 8)) & 1)\n bitmap[Int(j / 8)] &= ~(1 << (j % 8))\n }\n }\n\n // inodes bitmap goes into second bitmap block\n for i in 0.. self.inodes.count {\n continue\n }\n let inode = self.inodes[Int(ino) - 1]\n if ino > 10 && inode.pointee.linksCount == 0 { // deleted files\n continue\n }\n bitmap[Int(self.blockSize) + Int(i / 8)] |= 1 << (i % 8)\n inodes += 1\n if inode.pointee.mode.isDir() {\n dirs += 1\n }\n }\n\n for i in (blockGroupSize.inodesPerGroup / 8)...init(repeating: 0, count: 1024))\n\n let computedInodes = totalGroups * blockGroupSize.inodesPerGroup\n var blocksCount = totalGroups * self.blocksPerGroup\n while blocksCount < totalBlocks {\n blocksCount = UInt64(totalBlocks)\n }\n let totalFreeBlocks: UInt64\n if totalBlocks > blocksCount {\n totalFreeBlocks = 0\n } else {\n totalFreeBlocks = blocksCount - totalBlocks\n }\n var superblock = SuperBlock()\n superblock.inodesCount = computedInodes.lo\n superblock.blocksCountLow = blocksCount.lo\n superblock.blocksCountHigh = blocksCount.hi\n superblock.freeBlocksCountLow = totalFreeBlocks.lo\n superblock.freeBlocksCountHigh = totalFreeBlocks.hi\n let freeInodesCount = computedInodes.lo - totalInodes\n superblock.freeInodesCount = freeInodesCount\n superblock.firstDataBlock = 0\n superblock.logBlockSize = 2\n superblock.logClusterSize = 2\n superblock.blocksPerGroup = self.blocksPerGroup\n superblock.clustersPerGroup = self.blocksPerGroup\n superblock.inodesPerGroup = blockGroupSize.inodesPerGroup\n superblock.magic = EXT4.SuperBlockMagic\n superblock.state = 1 // cleanly unmounted\n superblock.errors = 1 // continue on error\n superblock.creatorOS = 3 // freeBSD\n superblock.revisionLevel = 1 // dynamic inode sizes\n superblock.firstInode = EXT4.FirstInode\n superblock.lpfInode = EXT4.LostAndFoundInode\n superblock.inodeSize = UInt16(EXT4.InodeSize)\n superblock.featureCompat = CompatFeature.sparseSuper2 | CompatFeature.extAttr\n superblock.featureIncompat =\n IncompatFeature.filetype | IncompatFeature.extents | IncompatFeature.flexBg | IncompatFeature.inlineData\n superblock.featureRoCompat =\n RoCompatFeature.largeFile | RoCompatFeature.hugeFile | RoCompatFeature.extraIsize\n superblock.minExtraIsize = EXT4.ExtraIsize\n superblock.wantExtraIsize = EXT4.ExtraIsize\n superblock.logGroupsPerFlex = 31\n superblock.uuid = UUID().uuid\n try withUnsafeLittleEndianBytes(of: superblock) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n try self.handle.write(contentsOf: Array.init(repeating: 0, count: 2048))\n }\n\n // MARK: Private Methods and Properties\n private var handle: FileHandle\n private var inodes: [Ptr]\n private var tree: FileTree\n private var deletedBlocks: [(start: UInt32, end: UInt32)] = []\n\n private var pos: UInt64 {\n guard let offset = try? self.handle.offset() else {\n return 0\n }\n return offset\n }\n\n private var currentBlock: UInt32 {\n self.pos / self.blockSize\n }\n\n private func seek(block: UInt32) throws {\n try self.handle.seek(toOffset: UInt64(block) * blockSize)\n }\n\n private func commitInodeTable(blockGroups: UInt32, inodesPerGroup: UInt32) throws -> UInt64 {\n // inodeTable must go into a new block\n if self.pos % blockSize != 0 {\n try seek(block: currentBlock + 1)\n }\n let inodeTableOffset = UInt64(currentBlock)\n\n let inodeSize = MemoryLayout.size\n // Write InodeTable\n for inode in self.inodes {\n try withUnsafeLittleEndianBytes(of: inode.pointee) { bytes in\n try handle.write(contentsOf: bytes)\n }\n try self.handle.write(\n contentsOf: Array.init(repeating: 0, count: Int(EXT4.InodeSize) - inodeSize))\n }\n let tableSize: UInt64 = UInt64(EXT4.InodeSize) * blockGroups * inodesPerGroup\n let rest = tableSize - uint32(self.inodes.count) * EXT4.InodeSize\n let zeroBlock = Array.init(repeating: 0, count: Int(self.blockSize))\n for _ in 0..<(rest / self.blockSize) {\n try self.handle.write(contentsOf: zeroBlock)\n }\n try self.handle.write(contentsOf: Array.init(repeating: 0, count: Int(rest % self.blockSize)))\n return inodeTableOffset\n }\n\n // optimizes the distribution of blockGroups to obtain the lowest number of blockGroups needed to\n // represent all the inodes and all the blocks in the FS\n private func optimizeBlockGroupLayout(blocks: UInt32, inodes: UInt32) -> (\n blockGroups: UInt32, inodesPerGroup: UInt32\n ) {\n // counts the number of blockGroups given a particular inodesPerGroup size\n let groupCount: (_ blocks: UInt32, _ inodes: UInt32, _ inodesPerGroup: UInt32) -> UInt32 = {\n blocks, inodes, inodesPerGroup in\n let inodeBlocksPerGroup: UInt32 = inodesPerGroup * EXT4.InodeSize / self.blockSize\n let dataBlocksPerGroup: UInt32 = self.blocksPerGroup - inodeBlocksPerGroup - 2 // save room for the bitmaps\n // Increase the block count to ensure there are enough groups for all the inodes.\n let minBlocks: UInt32 = (inodes - 1) / inodesPerGroup * dataBlocksPerGroup + 1\n var updatedBlocks = blocks\n if blocks < minBlocks {\n updatedBlocks = minBlocks\n }\n return (updatedBlocks + dataBlocksPerGroup - 1) / dataBlocksPerGroup\n }\n\n var groups: UInt32 = UInt32.max\n var inodesPerGroup: UInt32 = 0\n let inc = Int(self.blockSize * 512) / Int(EXT4.InodeSize) // inodesPerGroup\n // minimizes the number of blockGroups needed to its lowest value\n for ipg in stride(from: inc, through: Int(self.maxInodesPerGroup), by: inc) {\n let g = groupCount(blocks, inodes, UInt32(ipg))\n if g < groups {\n groups = g\n inodesPerGroup = UInt32(ipg)\n }\n }\n return (groups, inodesPerGroup)\n }\n\n private func commit(_ parentPtr: Ptr?, _ nodePtr: Ptr) throws {\n let node = nodePtr.pointee\n let inodePtr = self.inodes[Int(node.inode) - 1]\n var inode = inodePtr.pointee\n guard inode.linksCount > 0 else {\n return\n }\n if node.link != nil {\n return\n }\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n if inode.mode.isDir() {\n let startBlock = self.currentBlock\n var left: Int = Int(self.blockSize)\n try writeDirEntry(name: \".\", inode: node.inode, left: &left)\n if let parent = parentPtr {\n try writeDirEntry(name: \"..\", inode: parent.pointee.inode, left: &left)\n } else {\n try writeDirEntry(name: \"..\", inode: node.inode, left: &left)\n }\n var sortedChildren = Array(node.children)\n sortedChildren.sort { left, right in\n left.pointee.inode < right.pointee.inode\n }\n for childPtr in sortedChildren {\n let child = childPtr.pointee\n try writeDirEntry(name: child.name, inode: child.inode, left: &left, link: child.link)\n }\n try finishDirEntryBlock(&left)\n let endBlock = self.currentBlock\n let size: UInt64 = UInt64(endBlock - startBlock) * self.blockSize\n inode.sizeLow = size.lo\n inode.sizeHigh = size.hi\n inodePtr.initialize(to: inode)\n node.blocks = (startBlock, endBlock)\n nodePtr.initialize(to: node)\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n inode = try self.writeExtents(inode, (startBlock, endBlock))\n inodePtr.initialize(to: inode)\n }\n }\n\n private func fillExtents(\n node: inout ExtentLeafNode, numExtents: UInt32, numBlocks: UInt32, start: UInt32, offset: UInt32\n ) {\n for i in 0.. EXT4.MaxBlocksPerExtent {\n length = EXT4.MaxBlocksPerExtent\n }\n let extentStart: UInt32 = start + extentBlock\n let extent = ExtentLeaf(\n block: extentBlock,\n length: UInt16(length),\n startHigh: 0,\n startLow: extentStart\n )\n node.leaves.append(extent)\n }\n }\n\n private func writeExtents(_ inode: Inode, _ blocks: (start: UInt32, end: UInt32)) throws -> Inode {\n var inode = inode\n // rest of code assumes that extents MUST go into a new block\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n let dataBlocks = blocks.end - blocks.start\n let numExtents = (dataBlocks + EXT4.MaxBlocksPerExtent - 1) / EXT4.MaxBlocksPerExtent\n var usedBlocks = dataBlocks\n let extentNodeSize = 12\n let extentsPerBlock = self.blockSize / extentNodeSize - 1\n var blockData: [UInt8] = .init(repeating: 0, count: 60)\n var blockIndex: Int = 0\n switch numExtents {\n case 0:\n return inode // noop\n case 1..<5:\n let extentHeader = ExtentHeader(\n magic: EXT4.ExtentHeaderMagic,\n entries: UInt16(numExtents),\n max: 4,\n depth: 0,\n generation: 0)\n\n var node = ExtentLeafNode(header: extentHeader, leaves: [])\n fillExtents(node: &node, numExtents: numExtents, numBlocks: dataBlocks, start: blocks.start, offset: 0)\n withUnsafeLittleEndianBytes(of: node.header) { bytes in\n for b in bytes {\n blockData[blockIndex] = b\n blockIndex = blockIndex + 1\n }\n }\n for leaf in node.leaves {\n withUnsafeLittleEndianBytes(of: leaf) { bytes in\n for b in bytes {\n blockData[blockIndex] = b\n blockIndex = blockIndex + 1\n }\n }\n }\n case 5..<4 * UInt32(extentsPerBlock) + 1:\n let extentBlocks = numExtents / extentsPerBlock + 1\n usedBlocks += extentBlocks\n let extentHeader = ExtentHeader(\n magic: EXT4.ExtentHeaderMagic,\n entries: UInt16(extentBlocks),\n max: 4,\n depth: 1,\n generation: 0\n )\n var root = ExtentIndexNode(header: extentHeader, indices: [])\n for i in 0.. extentsPerBlock {\n extentsInBlock = extentsPerBlock\n }\n let leafHeader = ExtentHeader(\n magic: EXT4.ExtentHeaderMagic,\n entries: UInt16(extentsInBlock),\n max: UInt16(extentsPerBlock),\n depth: 0,\n generation: 0\n )\n var leafNode = ExtentLeafNode(header: leafHeader, leaves: [])\n let offset = i * extentsPerBlock * EXT4.MaxBlocksPerExtent\n fillExtents(\n node: &leafNode, numExtents: extentsInBlock, numBlocks: dataBlocks,\n start: blocks.start + offset,\n offset: offset)\n try withUnsafeLittleEndianBytes(of: leafNode.header) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n for leaf in leafNode.leaves {\n try withUnsafeLittleEndianBytes(of: leaf) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n }\n let extentTail = ExtentTail(checksum: leafNode.leaves.last!.block)\n try withUnsafeLittleEndianBytes(of: extentTail) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n root.indices.append(extentIdx)\n }\n withUnsafeLittleEndianBytes(of: root.header) { bytes in\n for b in bytes {\n blockData[blockIndex] = b\n blockIndex = blockIndex + 1\n }\n }\n for leaf in root.indices {\n withUnsafeLittleEndianBytes(of: leaf) { bytes in\n for b in bytes {\n blockData[blockIndex] = b\n blockIndex = blockIndex + 1\n }\n }\n }\n default:\n throw Error.fileTooBig(UInt64(dataBlocks) * self.blockSize)\n }\n inode.block = (\n blockData[0], blockData[1], blockData[2], blockData[3], blockData[4], blockData[5], blockData[6],\n blockData[7],\n blockData[8], blockData[9],\n blockData[10], blockData[11], blockData[12], blockData[13], blockData[14], blockData[15], blockData[16],\n blockData[17], blockData[18], blockData[19],\n blockData[20], blockData[21], blockData[22], blockData[23], blockData[24], blockData[25], blockData[26],\n blockData[27], blockData[28], blockData[29],\n blockData[30], blockData[31], blockData[32], blockData[33], blockData[34], blockData[35], blockData[36],\n blockData[37], blockData[38], blockData[39],\n blockData[40], blockData[41], blockData[42], blockData[43], blockData[44], blockData[45], blockData[46],\n blockData[47], blockData[48], blockData[49],\n blockData[50], blockData[51], blockData[52], blockData[53], blockData[54], blockData[55], blockData[56],\n blockData[57], blockData[58], blockData[59]\n )\n // ensure that inode's block count includes extent blocks\n inode.blocksLow += usedBlocks\n inode.flags = InodeFlag.extents | inode.flags\n return inode\n }\n // writes a single directory entry\n private func writeDirEntry(name: String, inode: InodeNumber, left: inout Int, link: InodeNumber? = nil) throws {\n guard self.inodes[Int(inode) - 1].pointee.linksCount > 0 else {\n return\n }\n guard let nameData = name.data(using: .utf8) else {\n throw Error.invalidName(name)\n }\n let directoryEntrySize = MemoryLayout.size\n let rlb = directoryEntrySize + nameData.count\n let rl = (rlb + 3) & ~3\n if left < rl + 12 {\n try self.finishDirEntryBlock(&left)\n }\n var mode = self.inodes[Int(inode) - 1].pointee.mode\n var inodeNum = inode\n if let link {\n mode = self.inodes[Int(link) - 1].pointee.mode | 0o777\n inodeNum = link\n }\n let entry = DirectoryEntry(\n inode: inodeNum,\n recordLength: UInt16(rl),\n nameLength: UInt8(nameData.count),\n fileType: mode.fileType()\n )\n try withUnsafeLittleEndianBytes(of: entry) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n\n try nameData.withUnsafeBytes { buffer in\n try withUnsafeLittleEndianBuffer(of: buffer) { b in\n try self.handle.write(contentsOf: b)\n }\n }\n try self.handle.write(contentsOf: [UInt8](repeating: 0, count: rl - rlb))\n left = left - rl\n }\n\n private func finishDirEntryBlock(_ left: inout Int) throws {\n defer { left = Int(self.blockSize) }\n if left <= 0 {\n return\n }\n let entry = DirectoryEntry(\n inode: InodeNumber(0),\n recordLength: UInt16(left),\n nameLength: 0,\n fileType: 0\n )\n try withUnsafeLittleEndianBytes(of: entry) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n left = left - MemoryLayout.size\n if left < 4 {\n throw Error.noSpaceForTrailingDEntry\n }\n try self.handle.write(contentsOf: [UInt8](repeating: 0, count: Int(left)))\n }\n\n public enum Error: Swift.Error, CustomStringConvertible, Sendable, Equatable {\n case notDirectory(_ path: FilePath)\n case notFile(_ path: FilePath)\n case notFound(_ path: FilePath)\n case alreadyExists(_ path: FilePath)\n case unsupportedFiletype\n case maximumLinksExceeded(_ path: FilePath)\n case fileTooBig(_ size: UInt64)\n case invalidLink(_ path: FilePath)\n case invalidName(_ name: String)\n case noSpaceForTrailingDEntry\n case insufficientSpaceForGroupDescriptorBlocks\n case cannotCreateHardlinksToDirTarget(_ path: FilePath)\n case cannotTruncateFile(_ path: FilePath)\n case cannotCreateSparseFile(_ path: FilePath)\n case cannotResizeFS(_ size: UInt64)\n public var description: String {\n switch self {\n case .notDirectory(let path):\n return \"\\(path) is not a directory\"\n case .notFile(let path):\n return \"\\(path) is not a file\"\n case .notFound(let path):\n return \"\\(path) not found\"\n case .alreadyExists(let path):\n return \"\\(path) already exists\"\n case .unsupportedFiletype:\n return \"file type not supported\"\n case .maximumLinksExceeded(let path):\n return \"maximum links exceeded for path: \\(path)\"\n case .fileTooBig(let size):\n return \"\\(size) exceeds max file size (128 GiB)\"\n case .invalidLink(let path):\n return \"'\\(path)' is an invalid link\"\n case .invalidName(let name):\n return \"'\\(name)' is an invalid name\"\n case .noSpaceForTrailingDEntry:\n return \"not enough space for trailing dentry\"\n case .insufficientSpaceForGroupDescriptorBlocks:\n return \"not enough space for group descriptor blocks\"\n case .cannotCreateHardlinksToDirTarget(let path):\n return \"cannot create hard links to directory target: \\(path)\"\n case .cannotTruncateFile(let path):\n return \"cannot truncate file: \\(path)\"\n case .cannotCreateSparseFile(let path):\n return \"cannot create sparse file at \\(path)\"\n case .cannotResizeFS(let size):\n return \"cannot resize fs to \\(size) bytes\"\n }\n }\n }\n\n deinit {\n for inode in inodes {\n inode.deinitialize(count: 1)\n inode.deallocate()\n }\n self.inodes.removeAll()\n }\n }\n}\n\nextension Date {\n func fs() -> UInt64 {\n if self == Date.distantPast {\n return 0\n }\n\n let s = self.timeIntervalSince1970\n\n if s < -0x8000_0000 {\n return 0x8000_0000\n }\n\n if s > 0x3_7fff_ffff {\n return 0x3_7fff_ffff\n }\n\n let seconds = UInt64(s)\n let nanoseconds = UInt64(self.timeIntervalSince1970.truncatingRemainder(dividingBy: 1) * 1_000_000_000)\n\n return seconds | (nanoseconds << 34)\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/OSFile+Splice.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension OSFile {\n struct SpliceFile: Sendable {\n var file: OSFile\n var offset: Int\n let pipe = Pipe()\n\n var fileDescriptor: Int32 {\n file.fileDescriptor\n }\n\n var reader: Int32 {\n pipe.fileHandleForReading.fileDescriptor\n }\n\n var writer: Int32 {\n pipe.fileHandleForWriting.fileDescriptor\n }\n\n init(fd: Int32) {\n self.file = OSFile(fd: fd)\n self.offset = 0\n }\n\n init(handle: FileHandle) {\n self.file = OSFile(handle: handle)\n self.offset = 0\n }\n\n init(from: OSFile, withOffset: Int = 0) {\n self.file = from\n self.offset = withOffset\n }\n\n func close() throws {\n try self.file.close()\n }\n }\n\n static func splice(from: inout SpliceFile, to: inout SpliceFile, count: Int = 1 << 16) throws -> (read: Int, wrote: Int, action: IOAction) {\n let fromOffset = from.offset\n let toOffset = to.offset\n\n while true {\n while (from.offset - to.offset) < count {\n let toRead = count - (from.offset - to.offset)\n let bytesRead = Foundation.splice(from.fileDescriptor, nil, to.writer, nil, toRead, UInt32(bitPattern: SPLICE_F_MOVE | SPLICE_F_NONBLOCK))\n if bytesRead == -1 {\n if errno != EAGAIN && errno != EIO {\n throw POSIXError(.init(rawValue: errno)!)\n }\n break\n }\n if bytesRead == 0 {\n return (0, 0, .eof)\n }\n from.offset += bytesRead\n if bytesRead < toRead {\n break\n }\n }\n if from.offset == to.offset {\n return (from.offset - fromOffset, to.offset - toOffset, .success)\n }\n while to.offset < from.offset {\n let toWrite = from.offset - to.offset\n let bytesWrote = Foundation.splice(to.reader, nil, to.fileDescriptor, nil, toWrite, UInt32(bitPattern: SPLICE_F_MOVE | SPLICE_F_NONBLOCK))\n if bytesWrote == -1 {\n if errno != EAGAIN && errno != EIO {\n throw POSIXError(.init(rawValue: errno)!)\n }\n break\n }\n to.offset += bytesWrote\n if bytesWrote == 0 {\n return (from.offset - fromOffset, to.offset - toOffset, .brokenPipe)\n }\n if bytesWrote < toWrite {\n break\n }\n }\n }\n }\n}\n"], ["/containerization/Sources/Integration/Suite.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport NIOCore\n\nlet log = {\n LoggingSystem.bootstrap(StreamLogHandler.standardError)\n var log = Logger(label: \"com.apple.containerization\")\n log.logLevel = .debug\n return log\n}()\n\nenum IntegrationError: Swift.Error {\n case assert(msg: String)\n case noOutput\n}\n\nstruct SkipTest: Swift.Error, CustomStringConvertible {\n let reason: String\n\n var description: String {\n reason\n }\n}\n\n@main\nstruct IntegrationSuite: AsyncParsableCommand {\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.containerization\")\n }()\n\n private static let _contentStore: ContentStore = {\n try! LocalContentStore(path: appRoot.appending(path: \"content\"))\n }()\n\n private static let _imageStore: ImageStore = {\n try! ImageStore(\n path: appRoot,\n contentStore: contentStore\n )\n }()\n\n static let _testDir: URL = {\n FileManager.default.uniqueTemporaryDirectory(create: true)\n }()\n\n static var testDir: URL {\n _testDir\n }\n\n static var imageStore: ImageStore {\n _imageStore\n }\n\n static var contentStore: ContentStore {\n _contentStore\n }\n\n static let initImage = \"vminit:latest\"\n\n @Option(name: .shortAndLong, help: \"Path to a log file\")\n var bootlog: String\n\n @Option(name: .shortAndLong, help: \"Path to a kernel binary\")\n var kernel: String = \"./bin/vmlinux\"\n\n static func binPath(name: String) -> URL {\n URL(fileURLWithPath: FileManager.default.currentDirectoryPath)\n .appendingPathComponent(\"bin\")\n .appendingPathComponent(name)\n }\n\n func bootstrap() async throws -> (rootfs: Containerization.Mount, vmm: VirtualMachineManager, image: Containerization.Image) {\n let reference = \"ghcr.io/linuxcontainers/alpine:3.20\"\n let store = Self.imageStore\n\n let initImage = try await store.getInitImage(reference: Self.initImage)\n let initfs = try await {\n let p = Self.binPath(name: \"init.block\")\n do {\n return try await initImage.initBlock(at: p, for: .linuxArm)\n } catch let err as ContainerizationError {\n guard err.code == .exists else {\n throw err\n }\n return .block(\n format: \"ext4\",\n source: p.absolutePath(),\n destination: \"/\",\n options: [\"ro\"]\n )\n }\n }()\n\n var testKernel = Kernel(path: .init(filePath: kernel), platform: .linuxArm)\n testKernel.commandLine.addDebug()\n let image = try await Self.fetchImage(reference: reference, store: store)\n let platform = Platform(arch: \"arm64\", os: \"linux\", variant: \"v8\")\n\n let fs: Containerization.Mount = try await {\n let fsPath = Self.testDir.appending(component: \"rootfs.ext4\")\n do {\n let unpacker = EXT4Unpacker(blockSizeInBytes: 2.gib())\n return try await unpacker.unpack(image, for: platform, at: fsPath)\n } catch let err as ContainerizationError {\n if err.code == .exists {\n return .block(\n format: \"ext4\",\n source: fsPath.absolutePath(),\n destination: \"/\",\n options: []\n )\n }\n throw err\n }\n }()\n\n let clPath = Self.testDir.appending(component: \"rn.ext4\").absolutePath()\n try? FileManager.default.removeItem(atPath: clPath)\n\n let cl = try fs.clone(to: clPath)\n return (\n cl,\n VZVirtualMachineManager(\n kernel: testKernel,\n initialFilesystem: initfs,\n bootlog: bootlog\n ),\n image\n )\n }\n\n static func fetchImage(reference: String, store: ImageStore) async throws -> Containerization.Image {\n do {\n return try await store.get(reference: reference)\n } catch let error as ContainerizationError {\n if error.code == .notFound {\n return try await store.pull(reference: reference)\n }\n throw error\n }\n }\n\n static func adjustLimits() throws {\n var limits = rlimit()\n guard getrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n limits.rlim_cur = 65536\n limits.rlim_max = 65536\n\n guard setrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n }\n\n // Why does this exist?\n //\n // We need the virtualization entitlement to execute these tests.\n // There currently does not exist a straightforward way to do this\n // in a pure swift package.\n //\n // In order to not have a dependency on xcode, we create an executable\n // for our integration tests that can be signed then ran.\n //\n // We also can't import Testing as it expects to be run from a runner.\n // Hopefully this improves over time.\n func run() async throws {\n try Self.adjustLimits()\n let suiteStarted = CFAbsoluteTimeGetCurrent()\n log.info(\"starting integration suite\\n\")\n\n let tests: [String: () async throws -> Void] = [\n \"process true\": testProcessTrue,\n \"process false\": testProcessFalse,\n \"process echo hi\": testProcessEchoHi,\n \"process user\": testProcessUser,\n \"process stdin\": testProcessStdin,\n \"process home envvar\": testProcessHomeEnvvar,\n \"process custom home envvar\": testProcessCustomHomeEnvvar,\n \"process tty ensure TERM\": testProcessTtyEnvvar,\n \"multiple concurrent processes\": testMultipleConcurrentProcesses,\n \"multiple concurrent processes with output stress\": testMultipleConcurrentProcessesOutputStress,\n \"container hostname\": testHostname,\n \"container hosts\": testHostsFile,\n \"container mount\": testMounts,\n \"nested virt\": testNestedVirtualizationEnabled,\n \"container manager\": testContainerManagerCreate,\n ]\n\n var passed = 0\n var skipped = 0\n for (name, test) in tests {\n do {\n log.info(\"test \\(name) started...\")\n\n let started = CFAbsoluteTimeGetCurrent()\n try await test()\n let lasted = CFAbsoluteTimeGetCurrent() - started\n log.info(\"✅ test \\(name) complete in \\(lasted)s.\")\n passed += 1\n } catch let err as SkipTest {\n log.info(\"⏭️ skipped test: \\(err)\")\n skipped += 1\n } catch {\n log.error(\"❌ test \\(name) failed: \\(error)\")\n }\n }\n\n let ended = CFAbsoluteTimeGetCurrent() - suiteStarted\n var finishingText = \"\\n\\nIntegration suite completed in \\(ended)s with \\(passed)/\\(tests.count) passed\"\n if skipped > 0 {\n finishingText += \" and \\(skipped)/\\(tests.count) skipped\"\n }\n finishingText += \"!\"\n\n log.info(\"\\(finishingText)\")\n\n if passed + skipped < tests.count {\n log.error(\"❌\")\n throw ExitCode(1)\n }\n try? FileManager.default.removeItem(at: Self.testDir)\n }\n}\n"], ["/containerization/Sources/cctl/ImageCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\nextension Application {\n struct Images: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"images\",\n abstract: \"Manage images\",\n subcommands: [\n Get.self,\n Delete.self,\n Pull.self,\n Tag.self,\n Push.self,\n Save.self,\n Load.self,\n ]\n )\n\n func run() async throws {\n let store = Application.imageStore\n let images = try await store.list()\n\n print(\"REFERENCE\\tMEDIA TYPE\\tDIGEST\")\n for image in images {\n print(\"\\(image.reference)\\t\\(image.mediaType)\\t\\(image.digest)\")\n }\n }\n\n struct Delete: AsyncParsableCommand {\n @Argument var reference: String\n\n func run() async throws {\n let store = Application.imageStore\n try await store.delete(reference: reference)\n }\n }\n\n struct Tag: AsyncParsableCommand {\n @Argument var old: String\n @Argument var new: String\n\n func run() async throws {\n let store = Application.imageStore\n _ = try await store.tag(existing: old, new: new)\n }\n }\n\n struct Get: AsyncParsableCommand {\n @Argument var reference: String\n\n func run() async throws {\n let store = Application.imageStore\n let image = try await store.get(reference: reference)\n\n let index = try await image.index()\n\n let enc = JSONEncoder()\n enc.outputFormatting = .prettyPrinted\n let data = try enc.encode(ImageDisplay(reference: image.reference, index: index))\n print(String(data: data, encoding: .utf8)!)\n }\n }\n\n struct ImageDisplay: Codable {\n let reference: String\n let index: Index\n }\n\n struct Pull: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"pull\",\n abstract: \"Pull an image's contents into a content store\"\n )\n\n @Argument var ref: String\n\n @Option(name: .customLong(\"platform\"), help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platformString: String?\n\n @Option(\n name: .customLong(\"unpack-path\"), help: \"Path to a new directory to unpack the image into\",\n transform: { str in\n URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)\n })\n var unpackPath: String?\n\n @Flag(help: \"Pull via plain text http\") var http: Bool = false\n\n func run() async throws {\n let imageStore = Application.imageStore\n let platform: Platform? = try {\n if let platformString {\n return try Platform(from: platformString)\n }\n return nil\n }()\n\n let reference = try Reference.parse(ref)\n reference.normalize()\n let normalizedReference = reference.description\n if normalizedReference != ref {\n print(\"Reference resolved to \\(reference.description)\")\n }\n\n let image = try await Images.withAuthentication(ref: normalizedReference) { auth in\n try await imageStore.pull(reference: normalizedReference, platform: platform, insecure: http, auth: auth)\n }\n\n guard let image else {\n print(\"image pull failed\")\n Application.exit(withError: POSIXError(.EACCES))\n }\n\n print(\"image pulled\")\n guard let unpackPath else {\n return\n }\n guard !FileManager.default.fileExists(atPath: unpackPath) else {\n throw ContainerizationError(.exists, message: \"Directory already exists at \\(unpackPath)\")\n }\n let unpackUrl = URL(filePath: unpackPath)\n try FileManager.default.createDirectory(at: unpackUrl, withIntermediateDirectories: true)\n\n let unpacker = EXT4Unpacker.init(blockSizeInBytes: 2.gib())\n\n if let platform {\n let name = platform.description.replacingOccurrences(of: \"/\", with: \"-\")\n let _ = try await unpacker.unpack(image, for: platform, at: unpackUrl.appending(component: name))\n } else {\n for descriptor in try await image.index().manifests {\n if let referenceType = descriptor.annotations?[\"vnd.docker.reference.type\"], referenceType == \"attestation-manifest\" {\n continue\n }\n guard let descPlatform = descriptor.platform else {\n continue\n }\n let name = descPlatform.description.replacingOccurrences(of: \"/\", with: \"-\")\n let _ = try await unpacker.unpack(image, for: descPlatform, at: unpackUrl.appending(component: name))\n print(\"created snapshot for platform \\(descPlatform.description)\")\n }\n }\n }\n }\n\n struct Push: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"push\",\n abstract: \"Push an image to a remote registry\"\n )\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platformString: String?\n\n @Flag(help: \"Push via plain text http\") var http: Bool = false\n\n @Argument var ref: String\n\n func run() async throws {\n let imageStore = Application.imageStore\n let platform: Platform? = try {\n if let platformString {\n return try Platform(from: platformString)\n }\n return nil\n }()\n\n let reference = try Reference.parse(ref)\n reference.normalize()\n let normalizedReference = reference.description\n if normalizedReference != ref {\n print(\"Reference resolved to \\(reference.description)\")\n }\n\n try await Images.withAuthentication(ref: normalizedReference) { auth in\n try await imageStore.push(reference: normalizedReference, platform: platform, insecure: http, auth: auth)\n }\n print(\"image pushed\")\n }\n }\n\n struct Save: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"save\",\n abstract: \"Save one or more images to a tar archive\"\n )\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platform: String?\n\n @Option(name: .shortAndLong, help: \"Path to tar archive\")\n var output: String\n\n @Argument var reference: [String]\n\n func run() async throws {\n var p: Platform? = nil\n if let platform {\n p = try Platform(from: platform)\n }\n let store = Application.imageStore\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n try await store.save(references: reference, out: tempDir, platform: p)\n let writer = try ArchiveWriter(format: .pax, filter: .none, file: URL(filePath: output))\n try writer.archiveDirectory(tempDir)\n try writer.finishEncoding()\n print(\"image exported\")\n }\n }\n\n struct Load: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"load\",\n abstract: \"Load one or more images from a tar archive\"\n )\n\n @Option(name: .shortAndLong, help: \"Path to tar archive\")\n var input: String\n\n func run() async throws {\n let store = Application.imageStore\n let tarFile = URL(fileURLWithPath: input)\n let reader = try ArchiveReader(file: tarFile.absoluteURL)\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n try reader.extractContents(to: tempDir)\n let imported = try await store.load(from: tempDir)\n for image in imported {\n print(\"imported \\(image.reference)\")\n }\n }\n }\n\n private static func withAuthentication(\n ref: String, _ body: @Sendable @escaping (_ auth: Authentication?) async throws -> T?\n ) async throws -> T? {\n var authentication: Authentication?\n let ref = try Reference.parse(ref)\n guard let host = ref.resolvedDomain else {\n throw ContainerizationError(.invalidArgument, message: \"No host specified in image reference\")\n }\n authentication = Self.authenticationFromEnv(host: host)\n if let authentication {\n return try await body(authentication)\n }\n let keychain = KeychainHelper(id: Application.keychainID)\n authentication = try? keychain.lookup(domain: host)\n return try await body(authentication)\n }\n\n private static func authenticationFromEnv(host: String) -> Authentication? {\n let env = ProcessInfo.processInfo.environment\n guard env[\"REGISTRY_HOST\"] == host else {\n return nil\n }\n guard let user = env[\"REGISTRY_USERNAME\"], let password = env[\"REGISTRY_TOKEN\"] else {\n return nil\n }\n return BasicAuthentication(username: user, password: password)\n }\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/ProcessSupervisor.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nactor ProcessSupervisor {\n private let queue: DispatchQueue\n // `DispatchSourceSignal` is thread-safe.\n private nonisolated(unsafe) let source: DispatchSourceSignal\n private var processes = [ManagedProcess]()\n\n var log: Logger?\n\n func setLog(_ log: Logger?) {\n self.log = log\n }\n\n static let `default` = ProcessSupervisor()\n\n let poller: Epoll\n\n private init() {\n let queue = DispatchQueue(label: \"process-supervisor\")\n self.source = DispatchSource.makeSignalSource(signal: SIGCHLD, queue: queue)\n self.queue = queue\n self.poller = try! Epoll()\n let t = Thread {\n try! self.poller.run()\n }\n t.start()\n }\n\n func ready() {\n self.source.setEventHandler {\n do {\n self.log?.debug(\"received SIGCHLD, reaping processes\")\n try self.handleSignal()\n } catch {\n self.log?.error(\"reaping processes failed\", metadata: [\"error\": \"\\(error)\"])\n }\n }\n self.source.resume()\n }\n\n private func handleSignal() throws {\n dispatchPrecondition(condition: .onQueue(queue))\n\n self.log?.debug(\"starting to wait4 processes\")\n let exited = Reaper.reap()\n self.log?.debug(\"finished wait4 of \\(exited.count) processes\")\n\n self.log?.debug(\"checking for exit of managed process\", metadata: [\"exits\": \"\\(exited)\", \"processes\": \"\\(processes.count)\"])\n let exitedProcesses = self.processes.filter { proc in\n exited.contains { pid, _ in\n proc.pid == pid\n }\n }\n\n for proc in exitedProcesses {\n let pid = proc.pid\n if pid <= 0 {\n continue\n }\n\n if let status = exited[pid] {\n self.log?.debug(\n \"managed process exited\",\n metadata: [\n \"pid\": \"\\(pid)\",\n \"status\": \"\\(status)\",\n \"count\": \"\\(processes.count - 1)\",\n ])\n proc.setExit(status)\n self.processes.removeAll(where: { $0.pid == pid })\n }\n }\n }\n\n func start(process: ManagedProcess) throws -> Int32 {\n self.log?.debug(\"in supervisor lock to start process\")\n defer {\n self.log?.debug(\"out of supervisor lock to start process\")\n }\n\n do {\n self.processes.append(process)\n return try process.start()\n } catch {\n self.log?.error(\"process start failed \\(error)\", metadata: [\"process-id\": \"\\(process.id)\"])\n throw error\n }\n }\n\n deinit {\n self.log?.info(\"process supervisor deinit\")\n source.cancel()\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/StandardIO.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport Synchronization\n\nfinal class StandardIO: ManagedProcess.IO & Sendable {\n private struct State {\n var stdin: IOPair?\n var stdout: IOPair?\n var stderr: IOPair?\n\n var stdinPipe: Pipe?\n var stdoutPipe: Pipe?\n var stderrPipe: Pipe?\n }\n\n private let log: Logger?\n private let hostStdio: HostStdio\n private let state: Mutex\n\n init(\n stdio: HostStdio,\n log: Logger?\n ) {\n self.hostStdio = stdio\n self.log = log\n self.state = Mutex(State())\n }\n\n func start(process: inout Command) throws {\n try self.state.withLock {\n if let stdinPort = self.hostStdio.stdin {\n let inPipe = Pipe()\n process.stdin = inPipe.fileHandleForReading\n $0.stdinPipe = inPipe\n\n let type = VsockType(\n port: stdinPort,\n cid: VsockType.hostCID\n )\n let stdinSocket = try Socket(type: type, closeOnDeinit: false)\n try stdinSocket.connect()\n\n let pair = IOPair(\n readFrom: stdinSocket,\n writeTo: inPipe.fileHandleForWriting,\n logger: log\n )\n $0.stdin = pair\n\n try pair.relay()\n }\n\n if let stdoutPort = self.hostStdio.stdout {\n let outPipe = Pipe()\n process.stdout = outPipe.fileHandleForWriting\n $0.stdoutPipe = outPipe\n\n let type = VsockType(\n port: stdoutPort,\n cid: VsockType.hostCID\n )\n let stdoutSocket = try Socket(type: type, closeOnDeinit: false)\n try stdoutSocket.connect()\n\n let pair = IOPair(\n readFrom: outPipe.fileHandleForReading,\n writeTo: stdoutSocket,\n logger: log\n )\n $0.stdout = pair\n\n try pair.relay()\n }\n\n if let stderrPort = self.hostStdio.stderr {\n let errPipe = Pipe()\n process.stderr = errPipe.fileHandleForWriting\n $0.stderrPipe = errPipe\n\n let type = VsockType(\n port: stderrPort,\n cid: VsockType.hostCID\n )\n let stderrSocket = try Socket(type: type, closeOnDeinit: false)\n try stderrSocket.connect()\n\n let pair = IOPair(\n readFrom: errPipe.fileHandleForReading,\n writeTo: stderrSocket,\n logger: log\n )\n $0.stderr = pair\n\n try pair.relay()\n }\n }\n }\n\n // NOP\n func resize(size: Terminal.Size) throws {}\n\n func closeStdin() throws {\n self.state.withLock {\n if let stdin = $0.stdin {\n stdin.close()\n $0.stdin = nil\n }\n }\n }\n\n func closeAfterExec() throws {\n try self.state.withLock {\n if let stdin = $0.stdinPipe {\n try stdin.fileHandleForReading.close()\n }\n if let stdout = $0.stdoutPipe {\n try stdout.fileHandleForWriting.close()\n }\n if let stderr = $0.stderrPipe {\n try stderr.fileHandleForWriting.close()\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4Reader+Export.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationArchive\nimport Foundation\nimport SystemPackage\n\nextension EXT4.EXT4Reader {\n public func export(archive: FilePath) throws {\n let config = ArchiveWriterConfiguration(\n format: .paxRestricted, filter: .none, options: [Options.xattrformat(.schily)])\n let writer = try ArchiveWriter(configuration: config)\n try writer.open(file: archive.url)\n var items = self.tree.root.pointee.children\n let hardlinkedInodes = Set(self.hardlinks.values)\n var hardlinkTargets: [EXT4.InodeNumber: FilePath] = [:]\n\n while items.count > 0 {\n let itemPtr = items.removeFirst()\n let item = itemPtr.pointee\n let inode = try self.getInode(number: item.inode)\n let entry = WriteEntry()\n let mode = inode.mode\n let size: UInt64 = (UInt64(inode.sizeHigh) << 32) | UInt64(inode.sizeLow)\n entry.permissions = mode\n guard let path = item.path else {\n continue\n }\n if hardlinkedInodes.contains(item.inode) {\n hardlinkTargets[item.inode] = path\n }\n guard self.hardlinks[path] == nil else {\n continue\n }\n var attributes: [EXT4.ExtendedAttribute] = []\n let buffer: [UInt8] = EXT4.tupleToArray(inode.inlineXattrs)\n if !buffer.allZeros {\n try attributes.append(contentsOf: Self.readInlineExtendedAttributes(from: buffer))\n }\n if inode.xattrBlockLow != 0 {\n let block = inode.xattrBlockLow\n try self.seek(block: block)\n guard let buffer = try self.handle.read(upToCount: Int(self.blockSize)) else {\n throw EXT4.Error.couldNotReadBlock(block)\n }\n try attributes.append(contentsOf: Self.readBlockExtendedAttributes(from: [UInt8](buffer)))\n }\n\n var xattrs: [String: Data] = [:]\n for attribute in attributes {\n guard attribute.fullName != \"system.data\" else {\n continue\n }\n xattrs[attribute.fullName] = Data(attribute.value)\n }\n\n let pathStr = path.description\n entry.path = pathStr\n entry.size = Int64(size)\n entry.group = gid_t(inode.gid)\n entry.owner = uid_t(inode.uid)\n entry.creationDate = Date(fsTimestamp: UInt64((inode.ctimeExtra << 32) | inode.ctime))\n entry.modificationDate = Date(fsTimestamp: UInt64((inode.mtimeExtra << 32) | inode.mtime))\n entry.contentAccessDate = Date(fsTimestamp: UInt64((inode.atimeExtra << 32) | inode.atime))\n entry.xattrs = xattrs\n\n if mode.isDir() {\n entry.fileType = .directory\n for child in item.children {\n items.append(child)\n }\n if pathStr == \"\" {\n continue\n }\n try writer.writeEntry(entry: entry, data: nil)\n } else if mode.isReg() {\n entry.fileType = .regular\n var data = Data()\n var remaining: UInt64 = size\n if let block = item.blocks {\n for dataBlock in block.start.. self.blockSize {\n count = self.blockSize\n } else {\n count = remaining\n }\n guard let dataBytes = try self.handle.read(upToCount: Int(count)) else {\n throw EXT4.Error.couldNotReadBlock(dataBlock)\n }\n data.append(dataBytes)\n remaining -= UInt64(dataBytes.count)\n }\n }\n if let additionalBlocks = item.additionalBlocks {\n for block in additionalBlocks {\n for dataBlock in block.start.. self.blockSize {\n count = self.blockSize\n } else {\n count = remaining\n }\n guard let dataBytes = try self.handle.read(upToCount: Int(count)) else {\n throw EXT4.Error.couldNotReadBlock(dataBlock)\n }\n data.append(dataBytes)\n remaining -= UInt64(dataBytes.count)\n }\n }\n }\n try writer.writeEntry(entry: entry, data: data)\n } else if mode.isLink() {\n entry.fileType = .symbolicLink\n if size < 60 {\n let linkBytes = EXT4.tupleToArray(inode.block)\n entry.symlinkTarget = String(bytes: linkBytes, encoding: .utf8) ?? \"\"\n } else {\n if let block = item.blocks {\n try self.seek(block: block.start)\n guard let linkBytes = try self.handle.read(upToCount: Int(size)) else {\n throw EXT4.Error.couldNotReadBlock(block.start)\n }\n entry.symlinkTarget = String(bytes: linkBytes, encoding: .utf8) ?? \"\"\n }\n }\n try writer.writeEntry(entry: entry, data: nil)\n } else { // do not process sockets, fifo, character and block devices\n continue\n }\n }\n for (path, number) in self.hardlinks {\n guard let targetPath = hardlinkTargets[number] else {\n continue\n }\n let inode = try self.getInode(number: number)\n let entry = WriteEntry()\n entry.path = path.description\n entry.hardlink = targetPath.description\n entry.permissions = inode.mode\n entry.group = gid_t(inode.gid)\n entry.owner = uid_t(inode.uid)\n entry.creationDate = Date(fsTimestamp: UInt64((inode.ctimeExtra << 32) | inode.ctime))\n entry.modificationDate = Date(fsTimestamp: UInt64((inode.mtimeExtra << 32) | inode.mtime))\n entry.contentAccessDate = Date(fsTimestamp: UInt64((inode.atimeExtra << 32) | inode.atime))\n try writer.writeEntry(entry: entry, data: nil)\n }\n try writer.finishEncoding()\n }\n\n @available(*, deprecated, renamed: \"readInlineExtendedAttributes(from:)\")\n public static func readInlineExtenedAttributes(from buffer: [UInt8]) throws -> [EXT4.ExtendedAttribute] {\n try readInlineExtendedAttributes(from: buffer)\n }\n\n public static func readInlineExtendedAttributes(from buffer: [UInt8]) throws -> [EXT4.ExtendedAttribute] {\n let header = UInt32(littleEndian: buffer[0...4].withUnsafeBytes { $0.load(as: UInt32.self) })\n if header != EXT4.XAttrHeaderMagic {\n throw EXT4.FileXattrsState.Error.missingXAttrHeader\n }\n return try EXT4.FileXattrsState.read(buffer: buffer, start: 4, offset: 4)\n }\n\n @available(*, deprecated, renamed: \"readBlockExtendedAttributes(from:)\")\n public static func readBlockExtenedAttributes(from buffer: [UInt8]) throws -> [EXT4.ExtendedAttribute] {\n try readBlockExtendedAttributes(from: buffer)\n }\n\n public static func readBlockExtendedAttributes(from buffer: [UInt8]) throws -> [EXT4.ExtendedAttribute] {\n let header = UInt32(littleEndian: buffer[0...4].withUnsafeBytes { $0.load(as: UInt32.self) })\n if header != EXT4.XAttrHeaderMagic {\n throw EXT4.FileXattrsState.Error.missingXAttrHeader\n }\n\n return try EXT4.FileXattrsState.read(buffer: [UInt8](buffer), start: 32, offset: 0)\n }\n\n func seek(block: UInt32) throws {\n try self.handle.seek(toOffset: UInt64(block) * blockSize)\n }\n}\n\nextension Date {\n init(fsTimestamp: UInt64) {\n if fsTimestamp == 0 {\n self = Date.distantPast\n return\n }\n\n let seconds = Int64(fsTimestamp & 0x3_ffff_ffff)\n let nanoseconds = Double(fsTimestamp >> 34) / 1_000_000_000\n\n self = Date(timeIntervalSince1970: Double(seconds) + nanoseconds)\n }\n}\n#endif\n"], ["/containerization/Sources/ContainerizationOCI/Client/RegistryClient+Fetch.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport ContainerizationError\nimport ContainerizationExtras\nimport Crypto\nimport Foundation\nimport NIOFoundationCompat\n\n#if os(macOS)\nimport NIOFileSystem\n#endif\n\nextension RegistryClient {\n /// Resolve sends a HEAD request to the registry to find root manifest descriptor.\n /// This descriptor serves as an entry point to retrieve resources from the registry.\n public func resolve(name: String, tag: String) async throws -> Descriptor {\n var components = base\n\n // Make HEAD request to retrieve the digest header\n components.path = \"/v2/\\(name)/manifests/\\(tag)\"\n\n // The client should include an Accept header indicating which manifest content types it supports.\n let mediaTypes = [\n MediaTypes.dockerManifest,\n MediaTypes.dockerManifestList,\n MediaTypes.imageManifest,\n MediaTypes.index,\n \"*/*\",\n ]\n\n let headers = [\n (\"Accept\", mediaTypes.joined(separator: \", \"))\n ]\n\n return try await request(components: components, method: .HEAD, headers: headers) { response in\n guard response.status == .ok else {\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n\n guard let digest = response.headers.first(name: \"Docker-Content-Digest\") else {\n throw ContainerizationError(.invalidArgument, message: \"Missing required header Docker-Content-Digest\")\n }\n\n guard let type = response.headers.first(name: \"Content-Type\") else {\n throw ContainerizationError(.invalidArgument, message: \"Missing required header Content-Type\")\n }\n\n guard let sizeStr = response.headers.first(name: \"Content-Length\") else {\n throw ContainerizationError(.invalidArgument, message: \"Missing required header Content-Length\")\n }\n\n guard let size = Int64(sizeStr) else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot convert \\(sizeStr) to Int64\")\n }\n\n return Descriptor(mediaType: type, digest: digest, size: size)\n }\n }\n\n /// Fetch resource (either manifest or blob) to memory with JSON decoding.\n public func fetch(name: String, descriptor: Descriptor) async throws -> T {\n var components = base\n\n let manifestTypes = [\n MediaTypes.dockerManifest,\n MediaTypes.dockerManifestList,\n MediaTypes.imageManifest,\n MediaTypes.index,\n ]\n\n let isManifest = manifestTypes.contains(where: { $0 == descriptor.mediaType })\n let resource = isManifest ? \"manifests\" : \"blobs\"\n\n components.path = \"/v2/\\(name)/\\(resource)/\\(descriptor.digest)\"\n\n let mediaType = descriptor.mediaType\n if mediaType.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Missing media type for descriptor \\(descriptor.digest)\")\n }\n\n let headers = [\n (\"Accept\", mediaType)\n ]\n\n return try await requestJSON(components: components, headers: headers)\n }\n\n /// Fetch resource (either manifest or blob) to memory as raw `Data`.\n public func fetchData(name: String, descriptor: Descriptor) async throws -> Data {\n var components = base\n\n let manifestTypes = [\n MediaTypes.dockerManifest,\n MediaTypes.dockerManifestList,\n MediaTypes.imageManifest,\n MediaTypes.index,\n ]\n\n let isManifest = manifestTypes.contains(where: { $0 == descriptor.mediaType })\n let resource = isManifest ? \"manifests\" : \"blobs\"\n\n components.path = \"/v2/\\(name)/\\(resource)/\\(descriptor.digest)\"\n\n let mediaType = descriptor.mediaType\n if mediaType.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Missing media type for descriptor \\(descriptor.digest)\")\n }\n\n let headers = [\n (\"Accept\", mediaType)\n ]\n\n return try await requestData(components: components, headers: headers)\n }\n\n /// Fetch a blob from remote registry.\n /// This method is suitable for streaming data.\n public func fetchBlob(\n name: String,\n descriptor: Descriptor,\n closure: (Int64, HTTPClientResponse.Body) async throws -> Void\n ) async throws {\n var components = base\n components.path = \"/v2/\\(name)/blobs/\\(descriptor.digest)\"\n\n let mediaType = descriptor.mediaType\n if mediaType.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Missing media type for descriptor \\(descriptor.digest)\")\n }\n\n let headers = [\n (\"Accept\", mediaType)\n ]\n\n try await request(components: components, headers: headers) { response in\n guard response.status == .ok else {\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n\n // How many bytes to expect\n guard let expectedBytes = response.headers.first(name: \"Content-Length\").flatMap(Int64.init) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing required header Content-Length\")\n }\n\n try await closure(expectedBytes, response.body)\n }\n }\n\n #if os(macOS)\n /// Fetch a blob from remote registry and write the contents into a file in the provided directory.\n public func fetchBlob(name: String, descriptor: Descriptor, into file: URL, progress: ProgressHandler?) async throws -> (Int64, SHA256Digest) {\n var hasher = SHA256()\n var received: Int64 = 0\n let fs = NIOFileSystem.FileSystem.shared\n let handle = try await fs.openFile(forWritingAt: FilePath(file.absolutePath()), options: .newFile(replaceExisting: true))\n var writer = handle.bufferedWriter()\n do {\n try await self.fetchBlob(name: name, descriptor: descriptor) { (size, body) in\n var itr = body.makeAsyncIterator()\n while let buf = try await itr.next() {\n let readBytes = Int64(buf.readableBytes)\n received += readBytes\n let written = try await writer.write(contentsOf: buf)\n await progress?([\n ProgressEvent(event: \"add-size\", value: written)\n ])\n guard written == readBytes else {\n throw ContainerizationError(\n .internalError,\n message: \"Could not write \\(readBytes) bytes to file \\(file)\"\n )\n }\n hasher.update(data: buf.readableBytesView)\n }\n }\n try await writer.flush()\n try await handle.close()\n } catch {\n try? await handle.close()\n throw error\n }\n let computedDigest = hasher.finalize()\n return (received, computedDigest)\n }\n #else\n /// Fetch a blob from remote registry and write the contents into a file in the provided directory.\n public func fetchBlob(name: String, descriptor: Descriptor, into file: URL, progress: ProgressHandler?) async throws -> (Int64, SHA256Digest) {\n var hasher = SHA256()\n var received: Int64 = 0\n guard FileManager.default.createFile(atPath: file.path, contents: nil) else {\n throw ContainerizationError(.internalError, message: \"Cannot create file at path \\(file.path)\")\n }\n try await self.fetchBlob(name: name, descriptor: descriptor) { (size, body) in\n let fd = try FileHandle(forWritingTo: file)\n defer {\n try? fd.close()\n }\n var itr = body.makeAsyncIterator()\n while let buf = try await itr.next() {\n let readBytes = Int64(buf.readableBytes)\n received += readBytes\n await progress?([\n ProgressEvent(event: \"add-size\", value: readBytes)\n ])\n try fd.write(contentsOf: buf.readableBytesView)\n hasher.update(data: buf.readableBytesView)\n }\n }\n let computedDigest = hasher.finalize()\n return (received, computedDigest)\n }\n #endif\n}\n"], ["/containerization/Sources/ContainerizationOS/Linux/Epoll.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(Linux)\n\n#if canImport(Musl)\nimport Musl\n#elseif canImport(Glibc)\nimport Glibc\n#else\n#error(\"Epoll not supported on this platform\")\n#endif\n\nimport Foundation\nimport Synchronization\n\n/// Register file descriptors to receive events via Linux's\n/// epoll syscall surface.\npublic final class Epoll: Sendable {\n public typealias Mask = Int32\n public typealias Handler = (@Sendable (Mask) -> Void)\n\n private let epollFD: Int32\n private let handlers = SafeMap()\n private let pipe = Pipe() // to wake up a waiting epoll_wait\n\n public init() throws {\n let efd = epoll_create1(EPOLL_CLOEXEC)\n guard efd > 0 else {\n throw POSIXError.fromErrno()\n }\n self.epollFD = efd\n try self.add(pipe.fileHandleForReading.fileDescriptor) { _ in }\n }\n\n public func add(\n _ fd: Int32,\n mask: Int32 = EPOLLIN | EPOLLOUT, // HUP is always added\n handler: @escaping Handler\n ) throws {\n guard fcntl(fd, F_SETFL, O_NONBLOCK) == 0 else {\n throw POSIXError.fromErrno()\n }\n\n let events = EPOLLET | UInt32(bitPattern: mask)\n\n var event = epoll_event()\n event.events = events\n event.data.fd = fd\n\n try withUnsafeMutablePointer(to: &event) { ptr in\n while true {\n if epoll_ctl(self.epollFD, EPOLL_CTL_ADD, fd, ptr) == -1 {\n if errno == EAGAIN || errno == EINTR {\n continue\n }\n throw POSIXError.fromErrno()\n }\n break\n }\n }\n\n self.handlers.set(fd, handler)\n }\n\n /// Run the main epoll loop.\n ///\n /// max events to return in a single wait\n /// timeout in ms.\n /// -1 means block forever.\n /// 0 means return immediately if no events.\n public func run(maxEvents: Int = 128, timeout: Int32 = -1) throws {\n var events: [epoll_event] = .init(\n repeating: epoll_event(),\n count: maxEvents\n )\n\n while true {\n let n = epoll_wait(self.epollFD, &events, Int32(events.count), timeout)\n guard n >= 0 else {\n if errno == EINTR || errno == EAGAIN {\n continue // go back to epoll_wait\n }\n throw POSIXError.fromErrno()\n }\n\n if n == 0 {\n return // if epoll wait times out, then n will be 0\n }\n\n for i in 0.. Bool {\n errno == ENOENT || errno == EBADF || errno == EPERM\n }\n\n /// Shutdown the epoll handler.\n public func shutdown() throws {\n // wakes up epoll_wait and triggers a shutdown\n try self.pipe.fileHandleForWriting.close()\n }\n\n private final class SafeMap: Sendable {\n let dict = Mutex<[Key: Value]>([:])\n\n func set(_ key: Key, _ value: Value) {\n dict.withLock { @Sendable in\n $0[key] = value\n }\n }\n\n func get(_ key: Key) -> Value? {\n dict.withLock { @Sendable in\n $0[key]\n }\n }\n\n func del(_ key: Key) {\n dict.withLock { @Sendable in\n _ = $0.removeValue(forKey: key)\n }\n }\n }\n}\n\nextension Epoll.Mask {\n public var isHangup: Bool {\n (self & (EPOLLHUP | EPOLLERR | EPOLLRDHUP)) != 0\n }\n\n public var readyToRead: Bool {\n (self & EPOLLIN) != 0\n }\n\n public var readyToWrite: Bool {\n (self & EPOLLOUT) != 0\n }\n}\n\n#endif // os(Linux)\n"], ["/containerization/Sources/Containerization/Image/ImageStore/ImageStore+Export.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationIO\nimport ContainerizationOCI\nimport Crypto\nimport Foundation\n\nextension ImageStore {\n internal struct ExportOperation {\n let name: String\n let tag: String\n let contentStore: ContentStore\n let client: ContentClient\n let progress: ProgressHandler?\n\n init(name: String, tag: String, contentStore: ContentStore, client: ContentClient, progress: ProgressHandler? = nil) {\n self.contentStore = contentStore\n self.client = client\n self.progress = progress\n self.name = name\n self.tag = tag\n }\n\n @discardableResult\n internal func export(index: Descriptor, platforms: (Platform) -> Bool) async throws -> Descriptor {\n var pushQueue: [[Descriptor]] = []\n var current: [Descriptor] = [index]\n while !current.isEmpty {\n let children = try await self.getChildren(descs: current)\n let matches = try filterPlatforms(matcher: platforms, children).uniqued { $0.digest }\n pushQueue.append(matches)\n current = matches\n }\n let localIndexData = try await self.createIndex(from: index, matching: platforms)\n\n await updatePushProgress(pushQueue: pushQueue, localIndexData: localIndexData)\n\n // We need to work bottom up when pushing an image.\n // First, the tar blobs / config layers, then, the manifests and so on...\n // When processing a given \"level\", the requests maybe made in parallel.\n // We need to ensure that the child level has been uploaded fully\n // before uploading the parent level.\n try await withThrowingTaskGroup(of: Void.self) { group in\n for layerGroup in pushQueue.reversed() {\n for chunk in layerGroup.chunks(ofCount: 8) {\n for desc in chunk {\n guard let content = try await self.contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(desc.digest)\")\n }\n group.addTask {\n let readStream = try ReadStream(url: content.path)\n try await self.pushContent(descriptor: desc, stream: readStream)\n }\n }\n try await group.waitForAll()\n }\n }\n }\n\n // Lastly, we need to construct and push a new index, since we may\n // have pushed content only for specific platforms.\n let digest = SHA256.hash(data: localIndexData)\n let descriptor = Descriptor(\n mediaType: MediaTypes.index,\n digest: digest.digestString,\n size: Int64(localIndexData.count))\n let stream = ReadStream(data: localIndexData)\n try await self.pushContent(descriptor: descriptor, stream: stream)\n return descriptor\n }\n\n private func updatePushProgress(pushQueue: [[Descriptor]], localIndexData: Data) async {\n for layerGroup in pushQueue {\n for desc in layerGroup {\n await progress?([\n ProgressEvent(event: \"add-total-size\", value: desc.size),\n ProgressEvent(event: \"add-total-items\", value: 1),\n ])\n }\n }\n await progress?([\n ProgressEvent(event: \"add-total-size\", value: localIndexData.count),\n ProgressEvent(event: \"add-total-items\", value: 1),\n ])\n }\n\n private func createIndex(from index: Descriptor, matching: (Platform) -> Bool) async throws -> Data {\n guard let content = try await self.contentStore.get(digest: index.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(index.digest)\")\n }\n var idx: Index = try content.decode()\n let manifests = idx.manifests\n var matchedManifests: [Descriptor] = []\n var skippedPlatforms = false\n for manifest in manifests {\n guard let p = manifest.platform else {\n continue\n }\n if matching(p) {\n matchedManifests.append(manifest)\n } else {\n skippedPlatforms = true\n }\n }\n if !skippedPlatforms {\n return try content.data()\n }\n idx.manifests = matchedManifests\n return try JSONEncoder().encode(idx)\n }\n\n private func pushContent(descriptor: Descriptor, stream: ReadStream) async throws {\n do {\n let generator = {\n try stream.reset()\n return stream.stream\n }\n try await client.push(name: name, ref: tag, descriptor: descriptor, streamGenerator: generator, progress: progress)\n await progress?([\n ProgressEvent(event: \"add-size\", value: descriptor.size),\n ProgressEvent(event: \"add-items\", value: 1),\n ])\n } catch let err as ContainerizationError {\n guard err.code != .exists else {\n // We reported the total items and size and have to account for them in existing content.\n await progress?([\n ProgressEvent(event: \"add-size\", value: descriptor.size),\n ProgressEvent(event: \"add-items\", value: 1),\n ])\n return\n }\n throw err\n }\n }\n\n private func getChildren(descs: [Descriptor]) async throws -> [Descriptor] {\n var out: [Descriptor] = []\n for desc in descs {\n let mediaType = desc.mediaType\n guard let content = try await self.contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(desc.digest)\")\n }\n switch mediaType {\n case MediaTypes.index, MediaTypes.dockerManifestList:\n let index: Index = try content.decode()\n out.append(contentsOf: index.manifests)\n case MediaTypes.imageManifest, MediaTypes.dockerManifest:\n let manifest: Manifest = try content.decode()\n out.append(manifest.config)\n out.append(contentsOf: manifest.layers)\n default:\n continue\n }\n }\n return out\n }\n }\n}\n"], ["/containerization/Sources/Containerization/Agent/Vminitd.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport GRPC\nimport NIOPosix\n\n/// A remote connection into the vminitd Linux guest agent via a port (vsock).\n/// Used to modify the runtime environment of the Linux sandbox.\npublic struct Vminitd: Sendable {\n public typealias Client = Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClient\n\n // Default vsock port that the agent and client use.\n public static let port: UInt32 = 1024\n\n private static let defaultPath = \"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\n\n let client: Client\n\n public init(client: Client) {\n self.client = client\n }\n\n public init(connection: FileHandle, group: MultiThreadedEventLoopGroup) {\n self.client = .init(connection: connection, group: group)\n }\n\n /// Close the connection to the guest agent.\n public func close() async throws {\n try await client.close()\n }\n}\n\nextension Vminitd: VirtualMachineAgent {\n /// Perform the standard guest setup necessary for vminitd to be able to\n /// run containers.\n public func standardSetup() async throws {\n try await up(name: \"lo\")\n\n try await setenv(key: \"PATH\", value: Self.defaultPath)\n\n let mounts: [ContainerizationOCI.Mount] = [\n // NOTE: /proc is always done implicitly by the guest agent.\n .init(type: \"tmpfs\", source: \"tmpfs\", destination: \"/run\"),\n .init(type: \"sysfs\", source: \"sysfs\", destination: \"/sys\"),\n .init(type: \"tmpfs\", source: \"tmpfs\", destination: \"/tmp\"),\n .init(type: \"devpts\", source: \"devpts\", destination: \"/dev/pts\", options: [\"gid=5\", \"mode=620\", \"ptmxmode=666\"]),\n .init(type: \"cgroup2\", source: \"none\", destination: \"/sys/fs/cgroup\"),\n ]\n for mount in mounts {\n try await self.mount(mount)\n }\n }\n\n /// Mount a filesystem in the sandbox's environment.\n public func mount(_ mount: ContainerizationOCI.Mount) async throws {\n _ = try await client.mount(\n .with {\n $0.type = mount.type\n $0.source = mount.source\n $0.destination = mount.destination\n $0.options = mount.options\n })\n }\n\n /// Unmount a filesystem in the sandbox's environment.\n public func umount(path: String, flags: Int32) async throws {\n _ = try await client.umount(\n .with {\n $0.path = path\n $0.flags = flags\n })\n }\n\n /// Create a directory inside the sandbox's environment.\n public func mkdir(path: String, all: Bool, perms: UInt32) async throws {\n _ = try await client.mkdir(\n .with {\n $0.path = path\n $0.all = all\n $0.perms = perms\n })\n }\n\n public func createProcess(\n id: String,\n containerID: String?,\n stdinPort: UInt32?,\n stdoutPort: UInt32?,\n stderrPort: UInt32?,\n configuration: ContainerizationOCI.Spec,\n options: Data?\n ) async throws {\n let enc = JSONEncoder()\n _ = try await client.createProcess(\n .with {\n $0.id = id\n if let stdinPort {\n $0.stdin = stdinPort\n }\n if let stdoutPort {\n $0.stdout = stdoutPort\n }\n if let stderrPort {\n $0.stderr = stderrPort\n }\n if let containerID {\n $0.containerID = containerID\n }\n $0.configuration = try enc.encode(configuration)\n })\n }\n\n @discardableResult\n public func startProcess(id: String, containerID: String?) async throws -> Int32 {\n let request = Com_Apple_Containerization_Sandbox_V3_StartProcessRequest.with {\n $0.id = id\n if let containerID {\n $0.containerID = containerID\n }\n }\n let resp = try await client.startProcess(request)\n return resp.pid\n }\n\n public func signalProcess(id: String, containerID: String?, signal: Int32) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_KillProcessRequest.with {\n $0.id = id\n $0.signal = signal\n if let containerID {\n $0.containerID = containerID\n }\n }\n _ = try await client.killProcess(request)\n }\n\n public func resizeProcess(id: String, containerID: String?, columns: UInt32, rows: UInt32) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest.with {\n if let containerID {\n $0.containerID = containerID\n }\n $0.id = id\n $0.columns = columns\n $0.rows = rows\n }\n _ = try await client.resizeProcess(request)\n }\n\n public func waitProcess(id: String, containerID: String?, timeoutInSeconds: Int64? = nil) async throws -> Int32 {\n let request = Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest.with {\n $0.id = id\n if let containerID {\n $0.containerID = containerID\n }\n }\n var callOpts: CallOptions?\n if let timeoutInSeconds {\n var copts = CallOptions()\n copts.timeLimit = .timeout(.seconds(timeoutInSeconds))\n callOpts = copts\n }\n do {\n let resp = try await client.waitProcess(request, callOptions: callOpts)\n return resp.exitCode\n } catch {\n if let err = error as? GRPCError.RPCTimedOut {\n throw ContainerizationError(\n .timeout,\n message: \"failed to wait for process exit within timeout of \\(timeoutInSeconds!) seconds\",\n cause: err\n )\n }\n throw error\n }\n }\n\n public func deleteProcess(id: String, containerID: String?) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest.with {\n $0.id = id\n if let containerID {\n $0.containerID = containerID\n }\n }\n _ = try await client.deleteProcess(request)\n }\n\n public func closeProcessStdin(id: String, containerID: String?) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest.with {\n $0.id = id\n if let containerID {\n $0.containerID = containerID\n }\n }\n _ = try await client.closeProcessStdin(request)\n }\n\n public func up(name: String, mtu: UInt32? = nil) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest.with {\n $0.interface = name\n $0.up = true\n if let mtu { $0.mtu = mtu }\n }\n _ = try await client.ipLinkSet(request)\n }\n\n public func down(name: String) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest.with {\n $0.interface = name\n $0.up = false\n }\n _ = try await client.ipLinkSet(request)\n }\n\n /// Get an environment variable from the sandbox's environment.\n public func getenv(key: String) async throws -> String {\n let response = try await client.getenv(\n .with {\n $0.key = key\n })\n return response.value\n }\n\n /// Set an environment variable in the sandbox's environment.\n public func setenv(key: String, value: String) async throws {\n _ = try await client.setenv(\n .with {\n $0.key = key\n $0.value = value\n })\n }\n}\n\n/// Vminitd specific rpcs.\nextension Vminitd {\n /// Sets up an emulator in the guest.\n public func setupEmulator(binaryPath: String, configuration: Binfmt.Entry) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest.with {\n $0.binaryPath = binaryPath\n $0.name = configuration.name\n $0.type = configuration.type\n $0.offset = configuration.offset\n $0.magic = configuration.magic\n $0.mask = configuration.mask\n $0.flags = configuration.flags\n }\n _ = try await client.setupEmulator(request)\n }\n\n /// Sets the guest time.\n public func setTime(sec: Int64, usec: Int32) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_SetTimeRequest.with {\n $0.sec = sec\n $0.usec = usec\n }\n _ = try await client.setTime(request)\n }\n\n /// Set the provided sysctls inside the Sandbox's environment.\n public func sysctl(settings: [String: String]) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_SysctlRequest.with {\n $0.settings = settings\n }\n _ = try await client.sysctl(request)\n }\n\n /// Add an IP address to the sandbox's network interfaces.\n public func addressAdd(name: String, address: String) async throws {\n _ = try await client.ipAddrAdd(\n .with {\n $0.interface = name\n $0.address = address\n })\n }\n\n /// Set the default route in the sandbox's environment.\n public func routeAddDefault(name: String, gateway: String) async throws {\n _ = try await client.ipRouteAddDefault(\n .with {\n $0.interface = name\n $0.gateway = gateway\n })\n }\n\n /// Configure DNS within the sandbox's environment.\n public func configureDNS(config: DNS, location: String) async throws {\n _ = try await client.configureDns(\n .with {\n $0.location = location\n $0.nameservers = config.nameservers\n if let domain = config.domain {\n $0.domain = domain\n }\n $0.searchDomains = config.searchDomains\n $0.options = config.options\n })\n }\n\n /// Configure /etc/hosts within the sandbox's environment.\n public func configureHosts(config: Hosts, location: String) async throws {\n _ = try await client.configureHosts(config.toAgentHostsRequest(location: location))\n }\n\n /// Perform a sync call.\n public func sync() async throws {\n _ = try await client.sync(.init())\n }\n\n public func kill(pid: Int32, signal: Int32) async throws -> Int32 {\n let response = try await client.kill(\n .with {\n $0.pid = pid\n $0.signal = signal\n })\n return response.result\n }\n\n /// Syncing shutdown will send a SIGTERM to all processes\n /// and wait, perform a sync operation, then issue a SIGKILL\n /// to the remaining processes before syncing again.\n public func syncingShutdown() async throws {\n _ = try await self.kill(pid: -1, signal: SIGTERM)\n try await Task.sleep(for: .milliseconds(10))\n try await self.sync()\n\n _ = try await self.kill(pid: -1, signal: SIGKILL)\n try await Task.sleep(for: .milliseconds(10))\n try await self.sync()\n }\n}\n\nextension Hosts {\n func toAgentHostsRequest(location: String) -> Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest {\n Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.with {\n $0.location = location\n if let comment {\n $0.comment = comment\n }\n $0.entries = entries.map {\n let entry = $0\n return Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.HostsEntry.with {\n if let comment = entry.comment {\n $0.comment = comment\n }\n $0.ipAddress = entry.ipAddress\n $0.hostnames = entry.hostnames\n }\n }\n }\n }\n}\n\nextension Vminitd.Client {\n public init(socket: String, group: MultiThreadedEventLoopGroup) {\n var config = ClientConnection.Configuration.default(\n target: .unixDomainSocket(socket),\n eventLoopGroup: group\n )\n config.maximumReceiveMessageLength = Int(64.mib())\n config.connectionBackoff = ConnectionBackoff(retries: .upTo(5))\n\n self = .init(channel: ClientConnection(configuration: config))\n }\n\n public init(connection: FileHandle, group: MultiThreadedEventLoopGroup) {\n var config = ClientConnection.Configuration.default(\n target: .connectedSocket(connection.fileDescriptor),\n eventLoopGroup: group\n )\n config.maximumReceiveMessageLength = Int(64.mib())\n config.connectionBackoff = ConnectionBackoff(retries: .upTo(5))\n\n self = .init(channel: ClientConnection(configuration: config))\n }\n\n public func close() async throws {\n try await self.channel.close().get()\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/TerminalIO.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport Synchronization\n\nfinal class TerminalIO: ManagedProcess.IO & Sendable {\n private struct State {\n var stdin: IOPair?\n var stdout: IOPair?\n }\n\n private let parent: Terminal\n private let child: Terminal\n private let log: Logger?\n private let hostStdio: HostStdio\n private let state: Mutex\n\n init(\n stdio: HostStdio,\n log: Logger?\n ) throws {\n let pair = try Terminal.create()\n self.parent = pair.parent\n self.child = pair.child\n self.state = Mutex(State())\n self.hostStdio = stdio\n self.log = log\n }\n\n func resize(size: Terminal.Size) throws {\n try parent.resize(size: size)\n }\n\n func start(process: inout Command) throws {\n try self.state.withLock {\n let ptyHandle = self.child.handle\n let useHandles = self.hostStdio.stdin != nil || self.hostStdio.stdout != nil\n // We currently set stdin to the controlling terminal always, so\n // it must be a valid pty descriptor.\n process.stdin = useHandles ? ptyHandle : nil\n\n let stdoutHandle = useHandles ? ptyHandle : nil\n process.stdout = stdoutHandle\n process.stderr = stdoutHandle\n\n if let stdinPort = self.hostStdio.stdin {\n let type = VsockType(\n port: stdinPort,\n cid: VsockType.hostCID\n )\n let stdinSocket = try Socket(type: type, closeOnDeinit: false)\n try stdinSocket.connect()\n\n let pair = IOPair(\n readFrom: stdinSocket,\n writeTo: self.parent.handle,\n logger: self.log\n )\n $0.stdin = pair\n\n try pair.relay()\n }\n\n if let stdoutPort = self.hostStdio.stdout {\n let type = VsockType(\n port: stdoutPort,\n cid: VsockType.hostCID\n )\n let stdoutSocket = try Socket(type: type, closeOnDeinit: false)\n try stdoutSocket.connect()\n\n let pair = IOPair(\n readFrom: self.parent.handle,\n writeTo: stdoutSocket,\n logger: self.log\n )\n $0.stdout = pair\n\n try pair.relay()\n }\n }\n }\n\n func closeStdin() throws {\n self.state.withLock {\n $0.stdin?.close()\n }\n }\n\n func closeAfterExec() throws {\n try child.close()\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Reader.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\nextension EXT4 {\n /// The `EXT4Reader` opens a block device, parses the superblock, and loads group descriptors & inodes.\n public class EXT4Reader {\n public var superBlock: EXT4.SuperBlock {\n self._superBlock\n }\n\n let handle: FileHandle\n let _superBlock: EXT4.SuperBlock\n\n private var groupDescriptors: [UInt32: EXT4.GroupDescriptor] = [:]\n private var inodes: [InodeNumber: EXT4.Inode] = [:]\n\n var hardlinks: [FilePath: InodeNumber] = [:]\n var tree: EXT4.FileTree = EXT4.FileTree(EXT4.RootInode, \".\")\n var blockSize: UInt64 {\n UInt64(1024 * (1 << _superBlock.logBlockSize))\n }\n\n private var groupDescriptorSize: UInt16 {\n if _superBlock.featureIncompat & EXT4.IncompatFeature.bit64.rawValue != 0 {\n return _superBlock.descSize\n }\n return UInt16(MemoryLayout.size)\n }\n\n public init(blockDevice: FilePath) throws {\n guard FileManager.default.fileExists(atPath: blockDevice.description) else {\n throw EXT4.Error.notFound(blockDevice.description)\n }\n\n guard let fileHandle = FileHandle(forReadingAtPath: blockDevice) else {\n throw Error.notFound(blockDevice.description)\n }\n self.handle = fileHandle\n try handle.seek(toOffset: EXT4.SuperBlockOffset)\n\n let superBlockSize = MemoryLayout.size\n guard let data = try? self.handle.read(upToCount: superBlockSize) else {\n throw EXT4.Error.couldNotReadSuperBlock(blockDevice.description, EXT4.SuperBlockOffset, superBlockSize)\n }\n let sb = data.withUnsafeBytes { ptr in\n ptr.loadLittleEndian(as: EXT4.SuperBlock.self)\n }\n guard sb.magic == EXT4.SuperBlockMagic else {\n throw EXT4.Error.invalidSuperBlock\n }\n self._superBlock = sb\n var items: [(item: Ptr, inode: InodeNumber)] = [\n (self.tree.root, EXT4.RootInode)\n ]\n while items.count > 0 {\n guard let item = items.popLast() else {\n break\n }\n let (itemPtr, inodeNum) = item\n let childItems = try self.children(of: inodeNum)\n let root = itemPtr.pointee\n for (itemName, itemInodeNum) in childItems {\n if itemName == \".\" || itemName == \"..\" {\n continue\n }\n\n if self.inodes[itemInodeNum] != nil {\n // we have seen this inode before, we will hard link this file to it\n guard let parentPath = itemPtr.pointee.path else {\n continue\n }\n let path = parentPath.join(itemName)\n self.hardlinks[path] = itemInodeNum\n continue\n }\n\n let blocks = try self.getExtents(inode: itemInodeNum)\n let itemTreeNodePtr = Ptr.allocate(capacity: 1)\n let itemTreeNode = FileTree.FileTreeNode(\n inode: itemInodeNum,\n name: itemName,\n parent: itemPtr,\n children: []\n )\n if let blocks {\n if blocks.count > 1 {\n itemTreeNode.additionalBlocks = Array(blocks.dropFirst())\n }\n itemTreeNode.blocks = blocks.first\n }\n itemTreeNodePtr.initialize(to: itemTreeNode)\n root.children.append(itemTreeNodePtr)\n itemPtr.initialize(to: root)\n let itemInode = try self.getInode(number: itemInodeNum)\n if itemInode.mode.isDir() {\n items.append((itemTreeNodePtr, itemInodeNum))\n }\n }\n }\n }\n\n deinit {\n try? self.handle.close()\n }\n\n private func readGroupDescriptor(_ number: UInt32) throws -> GroupDescriptor {\n let bs = UInt64(1024 * (1 << _superBlock.logBlockSize))\n let offset = bs + UInt64(number) * UInt64(self.groupDescriptorSize)\n try self.handle.seek(toOffset: offset)\n guard let data = try? self.handle.read(upToCount: MemoryLayout.size) else {\n throw EXT4.Error.couldNotReadGroup(number)\n }\n let gd = data.withUnsafeBytes { ptr in\n ptr.loadLittleEndian(as: EXT4.GroupDescriptor.self)\n }\n return gd\n }\n\n private func readInode(_ number: UInt32) throws -> Inode {\n let inodeGroupNumber = ((number - 1) / self._superBlock.inodesPerGroup)\n let numberInGroup = UInt64((number - 1) % self._superBlock.inodesPerGroup)\n\n let gd = try getGroupDescriptor(inodeGroupNumber)\n let inodeTableStart = UInt64(gd.inodeTableLow) * self.blockSize\n\n let inodeOffset: UInt64 = inodeTableStart + numberInGroup * UInt64(_superBlock.inodeSize)\n try self.handle.seek(toOffset: inodeOffset)\n guard let inodeData = try self.handle.read(upToCount: MemoryLayout.size) else {\n throw EXT4.Error.couldNotReadInode(number)\n }\n let inode = inodeData.withUnsafeBytes { ptr in\n ptr.loadLittleEndian(as: EXT4.Inode.self)\n }\n return inode\n }\n\n private func getDirTree(_ number: InodeNumber) throws -> [(String, InodeNumber)] {\n var children: [(String, InodeNumber)] = []\n let extents = try getExtents(inode: number) ?? []\n for (start, end) in extents {\n try self.seek(block: start)\n for i in 0..<(end - start) {\n guard let dirEntryBlock = try self.handle.read(upToCount: Int(self.blockSize)) else {\n throw EXT4.Error.couldNotReadBlock(start + i)\n }\n let childEntries = try getDirEntries(dirTree: dirEntryBlock)\n children.append(contentsOf: childEntries)\n }\n }\n return children.sorted { a, b in\n a.0 < b.0\n }\n }\n\n private func getDirEntries(dirTree: Data) throws -> [(String, InodeNumber)] {\n var children: [(String, InodeNumber)] = []\n var offset = 0\n while offset < dirTree.count {\n let length = MemoryLayout.size\n let dirEntry = dirTree.subdata(in: offset.. [(start: UInt32, end: UInt32)]? {\n let inode = try self.getInode(number: inode)\n let inodeBlock = Data(tupleToArray(inode.block))\n var offset = 0\n var extents: [(start: UInt32, end: UInt32)] = []\n\n let extentHeaderSize = MemoryLayout.size\n let extentIndexSize = MemoryLayout.size\n let extentLeafSize = MemoryLayout.size\n // read extent header\n let header = inodeBlock.subdata(in: offset.. Inode {\n if let inode = self.inodes[number] {\n return inode\n }\n\n let inode = try readInode(number)\n self.inodes[number] = inode\n return inode\n }\n\n func getGroupDescriptor(_ number: UInt32) throws -> GroupDescriptor {\n if let gd = self.groupDescriptors[number] {\n return gd\n }\n let gd = try readGroupDescriptor(number)\n self.groupDescriptors[number] = gd\n return gd\n }\n\n func children(of number: EXT4.InodeNumber) throws -> [(String, InodeNumber)] {\n try getDirTree(number)\n }\n }\n}\n"], ["/containerization/Sources/Containerization/TimeSyncer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Logging\n\nactor TimeSyncer: Sendable {\n private var task: Task?\n private var context: Vminitd?\n private let logger: Logger?\n\n init(logger: Logger?) {\n self.logger = logger\n }\n\n func start(context: Vminitd, interval: Duration = .seconds(30)) {\n precondition(task == nil, \"time syncer is already running\")\n self.context = context\n self.task = Task {\n while true {\n do {\n do {\n try await Task.sleep(for: interval)\n } catch {\n return\n }\n\n var timeval = timeval()\n guard gettimeofday(&timeval, nil) == 0 else {\n throw POSIXError.fromErrno()\n }\n\n try await context.setTime(\n sec: Int64(timeval.tv_sec),\n usec: Int32(timeval.tv_usec)\n )\n } catch {\n self.logger?.error(\"failed to sync time with guest agent: \\(error)\")\n }\n }\n }\n }\n\n func close() async throws {\n guard let task else {\n preconditionFailure(\"time syncer was already closed\")\n }\n\n task.cancel()\n try await self.context?.close()\n self.task = nil\n self.context = nil\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/OSFile.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nstruct OSFile: Sendable {\n private let fd: Int32\n\n enum IOAction: Equatable {\n case eof\n case again\n case success\n case brokenPipe\n case error(_ errno: Int32)\n }\n\n var closed: Bool {\n Foundation.fcntl(fd, F_GETFD) == -1 && errno == EBADF\n }\n\n var fileDescriptor: Int32 { fd }\n\n init(fd: Int32) {\n self.fd = fd\n }\n\n init(handle: FileHandle) {\n self.fd = handle.fileDescriptor\n }\n\n func close() throws {\n guard Foundation.close(self.fd) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n }\n\n func read(_ buffer: UnsafeMutableBufferPointer) -> (read: Int, action: IOAction) {\n if buffer.count == 0 {\n return (0, .success)\n }\n\n var bytesRead: Int = 0\n while true {\n let n = Foundation.read(\n self.fd,\n buffer.baseAddress!.advanced(by: bytesRead),\n buffer.count - bytesRead\n )\n if n == -1 {\n if errno == EAGAIN || errno == EIO {\n return (bytesRead, .again)\n }\n return (bytesRead, .error(errno))\n }\n\n if n == 0 {\n return (bytesRead, .eof)\n }\n\n bytesRead += n\n if bytesRead < buffer.count {\n continue\n }\n return (bytesRead, .success)\n }\n }\n\n func write(_ buffer: UnsafeMutableBufferPointer) -> (wrote: Int, action: IOAction) {\n if buffer.count == 0 {\n return (0, .success)\n }\n\n var bytesWrote: Int = 0\n while true {\n let n = Foundation.write(\n self.fd,\n buffer.baseAddress!.advanced(by: bytesWrote),\n buffer.count - bytesWrote\n )\n if n == -1 {\n if errno == EAGAIN || errno == EIO {\n return (bytesWrote, .again)\n }\n return (bytesWrote, .error(errno))\n }\n\n if n == 0 {\n return (bytesWrote, .brokenPipe)\n }\n\n bytesWrote += n\n if bytesWrote < buffer.count {\n continue\n }\n return (bytesWrote, .success)\n }\n }\n\n static func pipe() -> (read: Self, write: Self) {\n let pipe = Pipe()\n return (Self(handle: pipe.fileHandleForReading), Self(handle: pipe.fileHandleForWriting))\n }\n\n static func open(path: String) throws -> Self {\n try open(path: path, mode: O_RDONLY | O_CLOEXEC)\n }\n\n static func open(path: String, mode: Int32) throws -> Self {\n let fd = Foundation.open(path, mode)\n if fd < 0 {\n throw POSIXError(.init(rawValue: errno)!)\n }\n return Self(fd: fd)\n }\n}\n"], ["/containerization/Sources/Integration/ProcessTests.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Crypto\nimport Foundation\nimport Logging\n\nextension IntegrationSuite {\n func testProcessTrue() async throws {\n let id = \"test-process-true\"\n\n let bs = try await bootstrap()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/true\"]\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n }\n\n func testProcessFalse() async throws {\n let id = \"test-process-false\"\n\n let bs = try await bootstrap()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/false\"]\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 1 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 1\")\n }\n }\n\n final class BufferWriter: Writer {\n nonisolated(unsafe) var data = Data()\n\n func write(_ data: Data) throws {\n guard data.count > 0 else {\n return\n }\n self.data.append(data)\n }\n }\n\n final class StdinBuffer: ReaderStream {\n let data: Data\n\n init(data: Data) {\n self.data = data\n }\n\n func stream() -> AsyncStream {\n let (stream, cont) = AsyncStream.makeStream()\n cont.yield(self.data)\n cont.finish()\n return stream\n }\n }\n\n func testProcessEchoHi() async throws {\n let id = \"test-process-echo-hi\"\n let bs = try await bootstrap()\n\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/echo\", \"hi\"]\n config.process.stdout = buffer\n }\n\n do {\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 1\")\n }\n\n guard String(data: buffer.data, encoding: .utf8) == \"hi\\n\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned on stdout 'hi' != '\\(String(data: buffer.data, encoding: .utf8)!)'\")\n }\n } catch {\n try? await container.stop()\n throw error\n }\n }\n\n func testMultipleConcurrentProcesses() async throws {\n let id = \"test-concurrent-processes\"\n\n let bs = try await bootstrap()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/sleep\", \"1000\"]\n }\n\n do {\n try await container.create()\n try await container.start()\n\n try await withThrowingTaskGroup(of: Void.self) { group in\n for i in 0...80 {\n let exec = try await container.exec(\"exec-\\(i)\") { config in\n config.arguments = [\"/bin/true\"]\n }\n\n group.addTask {\n try await exec.start()\n let status = try await exec.wait()\n if status != 0 {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n try await exec.delete()\n }\n }\n\n // wait for all the exec'd processes.\n try await group.waitForAll()\n print(\"all group processes exit\")\n\n // kill the init process.\n try await container.kill(SIGKILL)\n let status = try await container.wait()\n try await container.stop()\n print(\"\\(status)\")\n }\n } catch {\n throw error\n }\n }\n\n func testMultipleConcurrentProcessesOutputStress() async throws {\n let id = \"test-concurrent-processes-output-stress\"\n let bs = try await bootstrap()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/sleep\", \"1000\"]\n }\n\n do {\n try await container.create()\n try await container.start()\n\n let buffer = BufferWriter()\n let exec = try await container.exec(\"expected-value\") { config in\n config.arguments = [\n \"sh\",\n \"-c\",\n \"dd if=/dev/random of=/tmp/bytes bs=1M count=20 status=none ; sha256sum /tmp/bytes\",\n ]\n config.stdout = buffer\n }\n\n try await exec.start()\n let status = try await exec.wait()\n if status != 0 {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n let output = String(data: buffer.data, encoding: .utf8)!\n let expected = String(output.split(separator: \" \").first!)\n try await withThrowingTaskGroup(of: Void.self) { group in\n for i in 0...80 {\n let idx = i\n group.addTask {\n let buffer = BufferWriter()\n let exec = try await container.exec(\"exec-\\(idx)\") { config in\n config.arguments = [\"cat\", \"/tmp/bytes\"]\n config.stdout = buffer\n }\n try await exec.start()\n\n let status = try await exec.wait()\n if status != 0 {\n throw IntegrationError.assert(msg: \"process \\(idx) status \\(status) != 0\")\n }\n\n var hasher = SHA256()\n hasher.update(data: buffer.data)\n let hash = hasher.finalize().digestString.trimmingDigestPrefix\n guard hash == expected else {\n throw IntegrationError.assert(\n msg: \"process \\(idx) output \\(hash) != expected \\(expected)\")\n }\n try await exec.delete()\n }\n }\n\n // wait for all the exec'd processes.\n try await group.waitForAll()\n print(\"all group processes exit\")\n\n // kill the init process.\n try await container.kill(SIGKILL)\n try await container.wait()\n try await container.stop()\n }\n }\n }\n\n func testProcessUser() async throws {\n let id = \"test-process-user\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/usr/bin/id\"]\n config.process.user = .init(uid: 1, gid: 1, additionalGids: [1])\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n let expected = \"uid=1(bin) gid=1(bin) groups=1(bin)\"\n\n guard String(data: buffer.data, encoding: .utf8) == \"\\(expected)\\n\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned on stdout '\\(expected)' != '\\(String(data: buffer.data, encoding: .utf8)!)'\")\n }\n }\n\n // Ensure if we ask for a terminal we set TERM.\n func testProcessTtyEnvvar() async throws {\n let id = \"test-process-tty-envvar\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"env\"]\n config.process.terminal = true\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n guard let str = String(data: buffer.data, encoding: .utf8) else {\n throw IntegrationError.assert(\n msg: \"failed to convert standard output to a UTF8 string\")\n }\n\n let homeEnvvar = \"TERM=xterm\"\n guard str.contains(homeEnvvar) else {\n throw IntegrationError.assert(\n msg: \"process should have TERM environment variable defined\")\n }\n }\n\n // Make sure we set HOME by default if we can find it in /etc/passwd in the guest.\n func testProcessHomeEnvvar() async throws {\n let id = \"test-process-home-envvar\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"env\"]\n config.process.user = .init(uid: 0, gid: 0)\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n guard let str = String(data: buffer.data, encoding: .utf8) else {\n throw IntegrationError.assert(\n msg: \"failed to convert standard output to a UTF8 string\")\n }\n\n let homeEnvvar = \"HOME=/root\"\n guard str.contains(homeEnvvar) else {\n throw IntegrationError.assert(\n msg: \"process should have HOME environment variable defined\")\n }\n }\n\n func testProcessCustomHomeEnvvar() async throws {\n let id = \"test-process-custom-home-envvar\"\n\n let bs = try await bootstrap()\n let customHomeEnvvar = \"HOME=/tmp/custom/home\"\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"sh\", \"-c\", \"echo HOME=$HOME\"]\n config.process.environmentVariables.append(customHomeEnvvar)\n config.process.user = .init(uid: 0, gid: 0)\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n guard let output = String(data: buffer.data, encoding: .utf8) else {\n throw IntegrationError.assert(msg: \"failed to convert stdout to UTF8\")\n }\n\n guard output.contains(customHomeEnvvar) else {\n throw IntegrationError.assert(msg: \"process should have preserved custom HOME environment variable, expected \\(customHomeEnvvar), got: \\(output)\")\n }\n }\n\n func testHostname() async throws {\n let id = \"test-container-hostname\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/hostname\"]\n config.hostname = \"foo-bar\"\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n let expected = \"foo-bar\"\n\n guard String(data: buffer.data, encoding: .utf8) == \"\\(expected)\\n\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned on stdout '\\(expected)' != '\\(String(data: buffer.data, encoding: .utf8)!)'\")\n }\n }\n\n func testHostsFile() async throws {\n let id = \"test-container-hosts-file\"\n\n let bs = try await bootstrap()\n let entry = Hosts.Entry.localHostIPV4(comment: \"Testaroo\")\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"cat\", \"/etc/hosts\"]\n config.hosts = Hosts(entries: [entry])\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n let expected = entry.rendered\n guard String(data: buffer.data, encoding: .utf8) == \"\\(expected)\\n\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned on stdout '\\(expected)' != '\\(String(data: buffer.data, encoding: .utf8)!)'\")\n }\n }\n\n func testProcessStdin() async throws {\n let id = \"test-container-stdin\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"cat\"]\n config.process.stdin = StdinBuffer(data: \"Hello from test\".data(using: .utf8)!)\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n let expected = \"Hello from test\"\n\n guard String(data: buffer.data, encoding: .utf8) == \"\\(expected)\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned on stdout '\\(expected)' != '\\(String(data: buffer.data, encoding: .utf8)!)'\")\n }\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/Server.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\nimport GRPC\nimport Logging\nimport Musl\nimport NIOCore\nimport NIOPosix\n\nfinal class Initd: Sendable {\n let log: Logger\n let state: State\n let group: MultiThreadedEventLoopGroup\n\n actor State {\n var containers: [String: ManagedContainer] = [:]\n var proxies: [String: VsockProxy] = [:]\n\n func get(container id: String) throws -> ManagedContainer {\n guard let ctr = self.containers[id] else {\n throw ContainerizationError(\n .notFound,\n message: \"container \\(id) not found\"\n )\n }\n return ctr\n }\n\n func add(container: ManagedContainer) throws {\n guard containers[container.id] == nil else {\n throw ContainerizationError(\n .exists,\n message: \"container \\(container.id) already exists\"\n )\n }\n containers[container.id] = container\n }\n\n func add(proxy: VsockProxy) throws {\n guard proxies[proxy.id] == nil else {\n throw ContainerizationError(\n .exists,\n message: \"proxy \\(proxy.id) already exists\"\n )\n }\n proxies[proxy.id] = proxy\n }\n\n func remove(proxy id: String) throws -> VsockProxy {\n guard let proxy = proxies.removeValue(forKey: id) else {\n throw ContainerizationError(\n .notFound,\n message: \"proxy \\(id) does not exist\"\n )\n }\n return proxy\n }\n\n func remove(container id: String) throws {\n guard let _ = containers.removeValue(forKey: id) else {\n throw ContainerizationError(\n .notFound,\n message: \"container \\(id) does not exist\"\n )\n }\n }\n }\n\n init(log: Logger, group: MultiThreadedEventLoopGroup) {\n self.log = log\n self.group = group\n self.state = State()\n }\n\n func serve(port: Int) async throws {\n try await withThrowingTaskGroup(of: Void.self) { group in\n log.debug(\"starting process supervisor\")\n\n await ProcessSupervisor.default.setLog(self.log)\n await ProcessSupervisor.default.ready()\n\n log.debug(\n \"booting grpc server on vsock\",\n metadata: [\n \"port\": \"\\(port)\"\n ])\n let server = try await Server.start(\n configuration: .default(\n target: .vsockAddress(.init(cid: .any, port: .init(port))),\n eventLoopGroup: self.group,\n serviceProviders: [self])\n ).get()\n log.info(\n \"grpc api serving on vsock\",\n metadata: [\n \"port\": \"\\(port)\"\n ])\n\n group.addTask {\n try await server.onClose.get()\n }\n try await group.next()\n group.cancelAll()\n }\n }\n}\n"], ["/containerization/Sources/cctl/RunCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\n\nextension Application {\n struct Run: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"run\",\n abstract: \"Run a container\"\n )\n\n @Option(name: [.customLong(\"image\"), .customShort(\"i\")], help: \"Image reference to base the container on\")\n var imageReference: String = \"docker.io/library/alpine:3.16\"\n\n @Option(name: .long, help: \"id for the container\")\n var id: String = \"cctl\"\n\n @Option(name: [.customLong(\"cpus\"), .customShort(\"c\")], help: \"Number of CPUs to allocate to the container\")\n var cpus: Int = 2\n\n @Option(name: [.customLong(\"memory\"), .customShort(\"m\")], help: \"Amount of memory in megabytes\")\n var memory: UInt64 = 1024\n\n @Option(name: .customLong(\"fs-size\"), help: \"The size to create the block filesystem as\")\n var fsSizeInMB: UInt64 = 2048\n\n @Option(name: .customLong(\"mount\"), help: \"Directory to share into the container (Example: /foo:/bar)\")\n var mounts: [String] = []\n\n @Option(name: .long, help: \"IP address with subnet\")\n var ip: String?\n\n @Option(name: .long, help: \"Gateway address\")\n var gateway: String?\n\n @Option(name: .customLong(\"ns\"), help: \"Nameserver addresses\")\n var nameservers: [String] = []\n\n @Option(\n name: [.customLong(\"kernel\"), .customShort(\"k\")], help: \"Kernel binary path\", completion: .file(),\n transform: { str in\n URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)\n })\n public var kernel: String\n\n @Option(name: .long, help: \"Current working directory\")\n var cwd: String = \"/\"\n\n @Argument var arguments: [String] = [\"/bin/sh\"]\n\n func run() async throws {\n let kernel = Kernel(\n path: URL(fileURLWithPath: kernel),\n platform: .linuxArm\n )\n let manager = try await ContainerManager(\n kernel: kernel,\n initfsReference: \"vminit:latest\",\n )\n let sigwinchStream = AsyncSignalHandler.create(notify: [SIGWINCH])\n\n let current = try Terminal.current\n try current.setraw()\n defer { current.tryReset() }\n\n let container = try await manager.create(\n id,\n reference: imageReference,\n rootfsSizeInBytes: fsSizeInMB.mib()\n ) { config in\n config.cpus = cpus\n config.memoryInBytes = memory.mib()\n config.process.setTerminalIO(terminal: current)\n config.process.arguments = arguments\n config.process.workingDirectory = cwd\n\n for mount in self.mounts {\n let paths = mount.split(separator: \":\")\n if paths.count != 2 {\n throw ContainerizationError(\n .invalidArgument,\n message: \"incorrect mount format detected: \\(mount)\"\n )\n }\n let host = String(paths[0])\n let guest = String(paths[1])\n let czMount = Containerization.Mount.share(\n source: host,\n destination: guest\n )\n config.mounts.append(czMount)\n }\n\n var hosts = Hosts.default\n if let ip {\n guard let gateway else {\n throw ContainerizationError(.invalidArgument, message: \"gateway must be specified\")\n }\n config.interfaces.append(NATInterface(address: ip, gateway: gateway))\n config.dns = .init(nameservers: [gateway])\n if nameservers.count > 0 {\n config.dns = .init(nameservers: nameservers)\n }\n hosts.entries.append(\n Hosts.Entry(\n ipAddress: ip,\n hostnames: [id]\n ))\n }\n config.hosts = hosts\n }\n\n defer {\n try? manager.delete(id)\n }\n\n try await container.create()\n try await container.start()\n\n // Resize the containers pty to the current terminal window.\n try? await container.resize(to: try current.size)\n\n try await withThrowingTaskGroup(of: Void.self) { group in\n group.addTask {\n for await _ in sigwinchStream.signals {\n try await container.resize(to: try current.size)\n }\n }\n\n try await container.wait()\n group.cancelAll()\n\n try await container.stop()\n }\n }\n\n private static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.containerization\")\n }()\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Platform.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// Source: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/config.go\n\nimport ContainerizationError\nimport Foundation\n\n/// Platform describes the platform which the image in the manifest runs on.\npublic struct Platform: Sendable, Equatable {\n public static var current: Self {\n var systemInfo = utsname()\n uname(&systemInfo)\n let arch = withUnsafePointer(to: &systemInfo.machine) {\n $0.withMemoryRebound(to: CChar.self, capacity: 1) {\n String(cString: $0)\n }\n }\n switch arch {\n case \"arm64\":\n return .init(arch: \"arm64\", os: \"linux\", variant: \"v8\")\n case \"x86_64\":\n return .init(arch: \"amd64\", os: \"linux\")\n default:\n fatalError(\"unsupported arch \\(arch)\")\n }\n }\n\n /// The computed description, for example, `linux/arm64/v8`.\n public var description: String {\n let architecture = architecture\n if let variant = variant {\n return \"\\(os)/\\(architecture)/\\(variant)\"\n }\n return \"\\(os)/\\(architecture)\"\n }\n\n /// The CPU architecture, for example, `amd64` or `ppc64`.\n public var architecture: String {\n switch _rawArch {\n case \"arm64\", \"arm\", \"aarch64\", \"armhf\", \"armel\":\n return \"arm64\"\n case \"x86_64\", \"x86-64\", \"amd64\":\n return \"amd64\"\n case \"386\", \"ppc64le\", \"i386\", \"s390x\", \"riscv64\":\n return _rawArch\n default:\n return _rawArch\n }\n }\n\n /// The operating system, for example, `linux` or `windows`.\n public var os: String {\n _rawOS\n }\n\n /// An optional field specifying the operating system version, for example on Windows `10.0.14393.1066`.\n public var osVersion: String?\n\n /// An optional field specifying an array of strings, each listing a required OS feature (for example on Windows `win32k`).\n public var osFeatures: [String]?\n\n /// An optional field specifying a variant of the CPU, for example `v7` to specify ARMv7 when architecture is `arm`.\n public var variant: String?\n\n /// The operation system of the image (eg. `linux`).\n private let _rawOS: String\n /// The CPU architecture (eg. `arm64`).\n private let _rawArch: String\n\n public init(arch: String, os: String, osVersion: String? = nil, osFeatures: [String]? = nil, variant: String? = nil) {\n self._rawArch = arch\n self._rawOS = os\n self.osVersion = osVersion\n self.osFeatures = osFeatures\n self.variant = variant\n }\n\n /// Initializes a new platform from a string.\n /// - Parameters:\n /// - platform: A `string` value representing the platform.\n /// ```swift\n /// // Create a new `ImagePlatform` from string.\n /// let platform = try Platform(from: \"linux/amd64\")\n /// ```\n /// ## Throws ##\n /// - Throws: `Error.missingOS` if input is empty\n /// - Throws: `Error.invalidOS` if os is not `linux`\n /// - Throws: `Error.missingArch` if only one `/` is present\n /// - Throws: `Error.invalidArch` if an unrecognized architecture is provided\n /// - Throws: `Error.invalidVariant` if a variant is provided, and it does not apply to the specified architecture\n public init(from platform: String) throws {\n let items = platform.split(separator: \"/\", maxSplits: 1)\n guard let osValue = items.first else {\n throw ContainerizationError(.invalidArgument, message: \"Missing OS in \\(platform)\")\n }\n switch osValue {\n case \"linux\":\n _rawOS = osValue.description\n case \"darwin\":\n _rawOS = osValue.description\n case \"windows\":\n _rawOS = osValue.description\n default:\n throw ContainerizationError(.invalidArgument, message: \"Unknown OS in \\(osValue)\")\n }\n guard items.count > 1 else {\n throw ContainerizationError(.invalidArgument, message: \"Missing architecture in \\(platform)\")\n }\n\n guard let archItems = items.last?.split(separator: \"/\", maxSplits: 1, omittingEmptySubsequences: false) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing architecture in \\(platform)\")\n }\n\n guard let archName = archItems.first else {\n throw ContainerizationError(.invalidArgument, message: \"Missing architecture in \\(platform)\")\n }\n\n switch archName {\n case \"arm\", \"armhf\", \"armel\":\n _rawArch = \"arm\"\n variant = \"v7\"\n case \"aarch64\", \"arm64\":\n variant = \"v8\"\n _rawArch = \"arm64\"\n case \"x86_64\", \"x86-64\", \"amd64\":\n _rawArch = \"amd64\"\n default:\n _rawArch = archName.description\n }\n\n if archItems.count == 2 {\n guard let archVariant = archItems.last else {\n throw ContainerizationError(.invalidArgument, message: \"Missing variant in \\(platform)\")\n }\n\n switch archName {\n case \"arm\":\n switch archVariant {\n case \"v5\", \"v6\", \"v7\", \"v8\":\n variant = archVariant.description\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n case \"armhf\":\n switch archVariant {\n case \"v7\":\n variant = \"v7\"\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n case \"armel\":\n switch archVariant {\n case \"v6\":\n variant = \"v6\"\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n case \"aarch64\", \"arm64\":\n switch archVariant {\n case \"v8\", \"8\":\n variant = \"v8\"\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n case \"x86_64\", \"x86-64\", \"amd64\":\n switch archVariant {\n case \"v1\":\n variant = nil\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n case \"i386\", \"386\", \"ppc64le\", \"riscv64\":\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n }\n }\n\n}\n\nextension Platform: Hashable {\n /**\n `~=` compares two platforms to check if **lhs** platform images are compatible with **rhs** platform\n This operator can be used to check if an image of **lhs** platform can run on **rhs**:\n - `true`: when **rhs**=`arm/v8`, **lhs** is any of `arm/v8`, `arm/v7`, `arm/v6` and `arm/v5`\n - `true`: when **rhs**=`arm/v7`, **lhs** is any of `arm/v7`, `arm/v6` and `arm/v5`\n - `true`: when **rhs**=`arm/v6`, **lhs** is any of `arm/v6` and `arm/v5`\n - `true`: when **rhs**=`amd64`, **lhs** is any of `amd64` and `386`\n - `true`: when **rhs**=**lhs**\n - `false`: otherwise\n - Parameters:\n - lhs: platform whose compatibility is being checked\n - rhs: platform against which compatibility is being checked\n - Returns: `true | false`\n */\n public static func ~= (lhs: Platform, rhs: Platform) -> Bool {\n if lhs.os == rhs.os {\n if lhs._rawArch == rhs._rawArch {\n switch rhs._rawArch {\n case \"arm\":\n guard let lVariant = lhs.variant else {\n return lhs == rhs\n }\n guard let rVariant = rhs.variant else {\n return lhs == rhs\n }\n switch rVariant {\n case \"v8\":\n switch lVariant {\n case \"v5\", \"v6\", \"v7\", \"v8\":\n return true\n default:\n return false\n }\n case \"v7\":\n switch lVariant {\n case \"v5\", \"v6\", \"v7\":\n return true\n default:\n return false\n }\n case \"v6\":\n switch lVariant {\n case \"v5\", \"v6\":\n return true\n default:\n return false\n }\n default:\n return lhs == rhs\n }\n default:\n return lhs == rhs\n }\n }\n if lhs._rawArch == \"386\" && rhs._rawArch == \"amd64\" {\n return true\n }\n }\n return false\n }\n\n /// `==` compares if **lhs** and **rhs** are the exact same platforms.\n public static func == (lhs: Platform, rhs: Platform) -> Bool {\n // NOTE:\n // If the platform struct was created by setting the fields directly and not using (from: String)\n // then, there is a possibility that for arm64 architecture, the variant may be set to nil\n // In that case, the variant should be assumed to v8\n if lhs.architecture == \"arm64\" && rhs.architecture == \"arm64\" {\n // The following checks effectively verify\n // that one operand has nil value and other has \"v8\"\n if lhs.variant == nil || rhs.variant == nil {\n if lhs.variant == \"v8\" || rhs.variant == \"v8\" {\n return true\n }\n }\n }\n\n let osEqual = lhs.os == rhs.os\n let archEqual = lhs.architecture == rhs.architecture\n let variantEqual = lhs.variant == rhs.variant\n\n return osEqual && archEqual && variantEqual\n }\n\n public func hash(into hasher: inout Swift.Hasher) {\n hasher.combine(description)\n }\n}\n\nextension Platform: Codable {\n\n enum CodingKeys: String, CodingKey {\n case os = \"os\"\n case architecture = \"architecture\"\n case variant = \"variant\"\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(os, forKey: .os)\n try container.encode(architecture, forKey: .architecture)\n try container.encodeIfPresent(variant, forKey: .variant)\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let architecture = try container.decodeIfPresent(String.self, forKey: .architecture)\n guard let architecture else {\n throw ContainerizationError(.invalidArgument, message: \"Missing architecture\")\n }\n let os = try container.decodeIfPresent(String.self, forKey: .os)\n guard let os else {\n throw ContainerizationError(.invalidArgument, message: \"Missing OS\")\n }\n let variant = try container.decodeIfPresent(String.self, forKey: .variant)\n self.init(arch: architecture, os: os, variant: variant)\n }\n}\n\npublic func createPlatformMatcher(for platform: Platform?) -> @Sendable (Platform) -> Bool {\n if let platform {\n return { other in\n platform == other\n }\n }\n return { _ in\n true\n }\n}\n\npublic func filterPlatforms(matcher: (Platform) -> Bool, _ descriptors: [Descriptor]) throws -> [Descriptor] {\n var outDescriptors: [Descriptor] = []\n for desc in descriptors {\n guard let p = desc.platform else {\n // pass along descriptor if the platform is not defined\n outDescriptors.append(desc)\n continue\n }\n if matcher(p) {\n outDescriptors.append(desc)\n }\n }\n return outDescriptors\n}\n"], ["/containerization/Sources/ContainerizationOS/Socket/UnixType.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if canImport(Musl)\nimport Musl\nlet _SOCK_STREAM = SOCK_STREAM\n#elseif canImport(Glibc)\nimport Glibc\nlet _SOCK_STREAM = Int32(SOCK_STREAM.rawValue)\n#elseif canImport(Darwin)\nimport Darwin\nlet _SOCK_STREAM = SOCK_STREAM\n#else\n#error(\"UnixType not supported on this platform.\")\n#endif\n\n/// Unix domain socket variant of `SocketType`.\npublic struct UnixType: SocketType, Sendable, CustomStringConvertible {\n public var domain: Int32 { AF_UNIX }\n public var type: Int32 { _SOCK_STREAM }\n public var description: String {\n path\n }\n\n public let path: String\n public let perms: mode_t?\n private let _addr: sockaddr_un\n private let _unlinkExisting: Bool\n\n private init(sockaddr: sockaddr_un) {\n let pathname: String = withUnsafePointer(to: sockaddr.sun_path) { ptr in\n let charPtr = UnsafeRawPointer(ptr).assumingMemoryBound(to: CChar.self)\n return String(cString: charPtr)\n }\n self._addr = sockaddr\n self.path = pathname\n self._unlinkExisting = false\n self.perms = nil\n }\n\n /// Mode and unlinkExisting only used if the socket is going to be a listening socket.\n public init(\n path: String,\n perms: mode_t? = nil,\n unlinkExisting: Bool = false\n ) throws {\n self.path = path\n self.perms = perms\n self._unlinkExisting = unlinkExisting\n var addr = sockaddr_un()\n addr.sun_family = sa_family_t(AF_UNIX)\n\n let socketName = path\n let nameLength = socketName.utf8.count\n\n #if os(macOS)\n // Funnily enough, this isn't limited by sun path on macOS even though\n // it's stated as so.\n let lengthLimit = 253\n #elseif os(Linux)\n let lengthLimit = MemoryLayout.size(ofValue: addr.sun_path)\n #endif\n\n guard nameLength < lengthLimit else {\n throw Error.nameTooLong(path)\n }\n\n _ = withUnsafeMutablePointer(to: &addr.sun_path.0) { ptr in\n socketName.withCString { strncpy(ptr, $0, nameLength) }\n }\n\n #if os(macOS)\n addr.sun_len = UInt8(MemoryLayout.size + MemoryLayout.size + socketName.utf8.count + 1)\n #endif\n self._addr = addr\n }\n\n public func accept(fd: Int32) throws -> (Int32, SocketType) {\n var clientFD: Int32 = -1\n var addr = sockaddr_un()\n\n clientFD = Syscall.retrying {\n var size = socklen_t(MemoryLayout.stride)\n return withUnsafeMutablePointer(to: &addr) { pointer in\n pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { pointer in\n sysAccept(fd, pointer, &size)\n }\n }\n }\n if clientFD < 0 {\n throw Socket.errnoToError(msg: \"accept failed\")\n }\n\n return (clientFD, UnixType(sockaddr: addr))\n }\n\n public func beforeBind(fd: Int32) throws {\n #if os(Linux)\n // Only Linux supports setting the mode of a socket before binding.\n if let perms = self.perms {\n guard fchmod(fd, perms) == 0 else {\n throw Socket.errnoToError(msg: \"fchmod failed\")\n }\n }\n #endif\n\n var rc: Int32 = 0\n if self._unlinkExisting {\n rc = sysUnlink(self.path)\n if rc != 0 && errno != ENOENT {\n throw Socket.errnoToError(msg: \"failed to remove old socket at \\(self.path)\")\n }\n }\n }\n\n public func beforeListen(fd: Int32) throws {\n #if os(macOS)\n if let perms = self.perms {\n guard chmod(self.path, perms) == 0 else {\n throw Socket.errnoToError(msg: \"chmod failed\")\n }\n }\n #endif\n }\n\n public func withSockAddr(_ closure: (UnsafePointer, UInt32) throws -> Void) throws {\n var addr = self._addr\n try withUnsafePointer(to: &addr) {\n let addrBytes = UnsafeRawPointer($0).assumingMemoryBound(to: sockaddr.self)\n try closure(addrBytes, UInt32(MemoryLayout.stride))\n }\n }\n}\n\nextension UnixType {\n /// `UnixType` errors.\n public enum Error: Swift.Error, CustomStringConvertible {\n case nameTooLong(_: String)\n\n public var description: String {\n switch self {\n case .nameTooLong(let name):\n return \"\\(name) is too long for a Unix Domain Socket path\"\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Socket/VsockType.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CShim\n\n#if canImport(Musl)\nimport Musl\n#elseif canImport(Glibc)\nimport Glibc\n#elseif canImport(Darwin)\nimport Darwin\n#else\n#error(\"VsockType not supported on this platform.\")\n#endif\n\n/// Vsock variant of `SocketType`.\npublic struct VsockType: SocketType, Sendable {\n public var domain: Int32 { AF_VSOCK }\n public var type: Int32 { _SOCK_STREAM }\n public var description: String {\n \"\\(cid):\\(port)\"\n }\n\n public static let anyCID: UInt32 = UInt32(bitPattern: -1)\n public static let hypervisorCID: UInt32 = 0x0\n // Supported on Linux 5.6+; otherwise, will need to use getLocalCID().\n public static let localCID: UInt32 = 0x1\n public static let hostCID: UInt32 = 0x2\n\n // socketFD is unused on Linux.\n public static func getLocalCID(socketFD: Int32) throws -> UInt32 {\n let request = VsockLocalCIDIoctl\n #if os(Linux)\n let fd = open(\"/dev/vsock\", O_RDONLY | O_CLOEXEC)\n if fd == -1 {\n throw Socket.errnoToError(msg: \"failed to open /dev/vsock\")\n }\n defer { close(fd) }\n #else\n let fd = socketFD\n #endif\n var cid: UInt32 = 0\n guard sysIoctl(fd, numericCast(request), &cid) != -1 else {\n throw Socket.errnoToError(msg: \"failed to get local cid\")\n }\n return cid\n }\n\n public let port: UInt32\n public let cid: UInt32\n\n private let _addr: sockaddr_vm\n\n public init(port: UInt32, cid: UInt32) {\n self.cid = cid\n self.port = port\n var sockaddr = sockaddr_vm()\n sockaddr.svm_family = sa_family_t(AF_VSOCK)\n sockaddr.svm_cid = cid\n sockaddr.svm_port = port\n self._addr = sockaddr\n }\n\n private init(sockaddr: sockaddr_vm) {\n self._addr = sockaddr\n self.cid = sockaddr.svm_cid\n self.port = sockaddr.svm_port\n }\n\n public func accept(fd: Int32) throws -> (Int32, SocketType) {\n var clientFD: Int32 = -1\n var addr = sockaddr_vm()\n\n while clientFD < 0 {\n var size = socklen_t(MemoryLayout.stride)\n clientFD = withUnsafeMutablePointer(to: &addr) { pointer in\n pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { pointer in\n sysAccept(fd, pointer, &size)\n }\n }\n if clientFD < 0 && errno != EINTR {\n throw Socket.errnoToError(msg: \"accept failed\")\n }\n }\n return (clientFD, VsockType(sockaddr: addr))\n }\n\n public func withSockAddr(_ closure: (UnsafePointer, UInt32) throws -> Void) throws {\n var addr = self._addr\n try withUnsafePointer(to: &addr) {\n let addrBytes = UnsafeRawPointer($0).assumingMemoryBound(to: sockaddr.self)\n try closure(addrBytes, UInt32(MemoryLayout.stride))\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/LocalOCILayoutClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport Crypto\nimport Foundation\nimport NIOCore\nimport NIOFoundationCompat\n\npackage final class LocalOCILayoutClient: ContentClient {\n let cs: LocalContentStore\n\n package init(root: URL) throws {\n self.cs = try LocalContentStore(path: root)\n }\n\n private func _fetch(digest: String) async throws -> Content {\n guard let c: Content = try await self.cs.get(digest: digest) else {\n throw Error.missingContent(digest)\n }\n return c\n }\n\n package func fetch(name: String, descriptor: Descriptor) async throws -> T {\n let c = try await self._fetch(digest: descriptor.digest)\n return try c.decode()\n }\n\n package func fetchBlob(name: String, descriptor: Descriptor, into file: URL, progress: ProgressHandler?) async throws -> (Int64, SHA256Digest) {\n let c = try await self._fetch(digest: descriptor.digest)\n let fileManager = FileManager.default\n let filePath = file.absolutePath()\n if !fileManager.fileExists(atPath: filePath) {\n let src = c.path\n try fileManager.copyItem(at: src, to: file)\n\n if let progress, let fileSize = fileManager.fileSize(atPath: filePath) {\n await progress([\n ProgressEvent(event: \"add-size\", value: fileSize)\n ])\n }\n }\n let size = try Int64(c.size())\n let digest = try c.digest()\n return (size, digest)\n }\n\n package func fetchData(name: String, descriptor: Descriptor) async throws -> Data {\n let c = try await self._fetch(digest: descriptor.digest)\n return try c.data()\n }\n\n package func push(\n name: String,\n ref: String,\n descriptor: Descriptor,\n streamGenerator: () throws -> T,\n progress: ProgressHandler?\n ) async throws where T.Element == ByteBuffer {\n let input = try streamGenerator()\n\n let (id, dir) = try await self.cs.newIngestSession()\n do {\n let into = dir.appendingPathComponent(descriptor.digest.trimmingDigestPrefix)\n guard FileManager.default.createFile(atPath: into.path, contents: nil) else {\n throw Error.cannotCreateFile\n }\n let fd = try FileHandle(forWritingTo: into)\n defer {\n try? fd.close()\n }\n var wrote = 0\n var hasher = SHA256()\n\n for try await buffer in input {\n wrote += buffer.readableBytes\n try fd.write(contentsOf: buffer.readableBytesView)\n hasher.update(data: buffer.readableBytesView)\n }\n try await self.cs.completeIngestSession(id)\n } catch {\n try await self.cs.cancelIngestSession(id)\n }\n }\n}\n\nextension LocalOCILayoutClient {\n private static let ociLayoutFileName = \"oci-layout\"\n private static let ociLayoutVersionString = \"imageLayoutVersion\"\n private static let ociLayoutIndexFileName = \"index.json\"\n\n package func loadIndexFromOCILayout(directory: URL) throws -> ContainerizationOCI.Index {\n let fm = FileManager.default\n let decoder = JSONDecoder()\n\n let ociLayoutFile = directory.appendingPathComponent(Self.ociLayoutFileName)\n guard fm.fileExists(atPath: ociLayoutFile.absolutePath()) else {\n throw ContainerizationError(.notFound, message: ociLayoutFile.absolutePath())\n }\n var data = try Data(contentsOf: ociLayoutFile)\n let ociLayout = try decoder.decode([String: String].self, from: data)\n guard ociLayout[Self.ociLayoutVersionString] != nil else {\n throw ContainerizationError(.empty, message: \"missing key \\(Self.ociLayoutVersionString) in \\(ociLayoutFile.absolutePath())\")\n }\n\n let indexFile = directory.appendingPathComponent(Self.ociLayoutIndexFileName)\n guard fm.fileExists(atPath: indexFile.absolutePath()) else {\n throw ContainerizationError(.notFound, message: indexFile.absolutePath())\n }\n data = try Data(contentsOf: indexFile)\n let index = try decoder.decode(ContainerizationOCI.Index.self, from: data)\n return index\n }\n\n package func createOCILayoutStructure(directory: URL, manifests: [Descriptor]) throws {\n let fm = FileManager.default\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.withoutEscapingSlashes]\n\n let ingestDir = directory.appendingPathComponent(\"ingest\")\n try? fm.removeItem(at: ingestDir)\n let ociLayoutContent: [String: String] = [\n Self.ociLayoutVersionString: \"1.0.0\"\n ]\n\n var data = try encoder.encode(ociLayoutContent)\n var p = directory.appendingPathComponent(Self.ociLayoutFileName).absolutePath()\n guard fm.createFile(atPath: p, contents: data) else {\n throw ContainerizationError(.internalError, message: \"failed to create file \\(p)\")\n }\n let idx = ContainerizationOCI.Index(schemaVersion: 2, manifests: manifests)\n data = try encoder.encode(idx)\n p = directory.appendingPathComponent(Self.ociLayoutIndexFileName).absolutePath()\n guard fm.createFile(atPath: p, contents: data) else {\n throw ContainerizationError(.internalError, message: \"failed to create file \\(p)\")\n }\n }\n\n package func setImageReferenceAnnotation(descriptor: inout Descriptor, reference: String) {\n var annotations = descriptor.annotations ?? [:]\n annotations[AnnotationKeys.containerizationImageName] = reference\n annotations[AnnotationKeys.containerdImageName] = reference\n annotations[AnnotationKeys.openContainersImageName] = reference\n descriptor.annotations = annotations\n }\n\n package func getImageReferencefromDescriptor(descriptor: Descriptor) -> String? {\n let annotations = descriptor.annotations\n guard let annotations else {\n return nil\n }\n\n // Annotations here do not conform to the OCI image specification.\n // The interpretation of the annotations \"org.opencontainers.image.ref.name\" and\n // \"io.containerd.image.name\" is under debate:\n // - OCI spec examples suggest it should be the image tag:\n // https://github.com/opencontainers/image-spec/blob/fbb4662eb53b80bd38f7597406cf1211317768f0/image-layout.md?plain=1#L175\n // - Buildkitd maintainers argue it should represent the full image name:\n // https://github.com/moby/buildkit/issues/4615#issuecomment-2521810830\n // Until a consensus is reached, the preference is given to \"com.apple.containerization.image.name\" and then to\n // using \"io.containerd.image.name\" as it is the next safest choice\n if let name = annotations[AnnotationKeys.containerizationImageName] {\n return name\n }\n if let name = annotations[AnnotationKeys.containerdImageName] {\n return name\n }\n if let name = annotations[AnnotationKeys.openContainersImageName] {\n return name\n }\n return nil\n }\n\n package enum Error: Swift.Error {\n case missingContent(_ digest: String)\n case unsupportedInput\n case cannotCreateFile\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/Formatter+Unpack.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationArchive\nimport Foundation\nimport ContainerizationOS\nimport SystemPackage\nimport ContainerizationExtras\n\nprivate typealias Hardlinks = [FilePath: FilePath]\n\nextension EXT4.Formatter {\n /// Unpack the provided archive on to the ext4 filesystem.\n public func unpack(reader: ArchiveReader, progress: ProgressHandler? = nil) throws {\n var hardlinks: Hardlinks = [:]\n for (entry, data) in reader {\n try Task.checkCancellation()\n guard var pathEntry = entry.path else {\n continue\n }\n\n defer {\n // Count the number of entries\n if let progress {\n Task {\n await progress([\n ProgressEvent(event: \"add-items\", value: 1)\n ])\n }\n }\n }\n\n pathEntry = preProcessPath(s: pathEntry)\n let path = FilePath(pathEntry)\n\n if path.base.hasPrefix(\".wh.\") {\n if path.base == \".wh..wh..opq\" { // whiteout directory\n try self.unlink(path: path.dir, directoryWhiteout: true)\n continue\n }\n let startIndex = path.base.index(path.base.startIndex, offsetBy: \".wh.\".count)\n let filePath = String(path.base[startIndex...])\n let dir: FilePath = path.dir\n try self.unlink(path: dir.join(filePath))\n continue\n }\n\n if let hardlink = entry.hardlink {\n let hl = preProcessPath(s: hardlink)\n hardlinks[path] = FilePath(hl)\n continue\n }\n let ts = FileTimestamps(\n access: entry.contentAccessDate, modification: entry.modificationDate, creation: entry.creationDate)\n switch entry.fileType {\n case .directory:\n try self.create(\n path: path, mode: EXT4.Inode.Mode(.S_IFDIR, entry.permissions), ts: ts, uid: entry.owner,\n gid: entry.group,\n xattrs: entry.xattrs)\n case .regular:\n let inputStream = InputStream(data: data)\n inputStream.open()\n try self.create(\n path: path, mode: EXT4.Inode.Mode(.S_IFREG, entry.permissions), ts: ts, buf: inputStream,\n uid: entry.owner,\n gid: entry.group, xattrs: entry.xattrs)\n inputStream.close()\n\n // Count the size of files\n if let progress {\n Task {\n let size = Int64(data.count)\n await progress([\n ProgressEvent(event: \"add-size\", value: size)\n ])\n }\n }\n case .symbolicLink:\n var symlinkTarget: FilePath?\n if let target = entry.symlinkTarget {\n symlinkTarget = FilePath(target)\n }\n try self.create(\n path: path, link: symlinkTarget, mode: EXT4.Inode.Mode(.S_IFLNK, entry.permissions), ts: ts,\n uid: entry.owner,\n gid: entry.group, xattrs: entry.xattrs)\n default:\n continue\n }\n }\n guard hardlinks.acyclic else {\n throw UnpackError.circularLinks\n }\n for (path, _) in hardlinks {\n if let resolvedTarget = try hardlinks.resolve(path) {\n try self.link(link: path, target: resolvedTarget)\n }\n }\n }\n\n /// Unpack an archive at the source URL on to the ext4 filesystem.\n public func unpack(\n source: URL,\n format: ContainerizationArchive.Format = .paxRestricted,\n compression: ContainerizationArchive.Filter = .gzip,\n progress: ProgressHandler? = nil\n ) throws {\n let reader = try ArchiveReader(\n format: format,\n filter: compression,\n file: source\n )\n try self.unpack(reader: reader, progress: progress)\n }\n\n private func preProcessPath(s: String) -> String {\n var p = s\n if p.hasPrefix(\"./\") {\n p = String(p.dropFirst())\n }\n if !p.hasPrefix(\"/\") {\n p = \"/\" + p\n }\n return p\n }\n}\n\n/// Common errors for unpacking an archive onto an ext4 filesystem.\npublic enum UnpackError: Swift.Error, CustomStringConvertible, Sendable, Equatable {\n /// The name is invalid.\n case invalidName(_ name: String)\n /// A circular link is found.\n case circularLinks\n\n /// The description of the error.\n public var description: String {\n switch self {\n case .invalidName(let name):\n return \"'\\(name)' is an invalid name\"\n case .circularLinks:\n return \"circular links found\"\n }\n }\n}\n\nextension Hardlinks {\n fileprivate var acyclic: Bool {\n for (_, target) in self {\n var visited: Set = [target]\n var next = target\n while let item = self[next] {\n if visited.contains(item) {\n return false\n }\n next = item\n visited.insert(next)\n }\n }\n return true\n }\n\n fileprivate func resolve(_ key: FilePath) throws -> FilePath? {\n let target = self[key]\n guard let target else {\n return nil\n }\n var next = target\n let visited: Set = [next]\n while let item = self[next] {\n if visited.contains(item) {\n throw UnpackError.circularLinks\n }\n next = item\n }\n return next\n }\n}\n#endif\n"], ["/containerization/Sources/ContainerizationOCI/Content/LocalContentStore.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// swiftlint:disable unused_optional_binding\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport Crypto\nimport Foundation\n\n/// A `ContentStore` implementation that stores content on the local filesystem.\npublic actor LocalContentStore: ContentStore {\n private static let encoder = JSONEncoder()\n\n private let _basePath: URL\n private let _ingestPath: URL\n private let _blobPath: URL\n private let _lock: AsyncLock\n\n private var activeIngestSessions: AsyncSet = AsyncSet([])\n\n /// Create a new `LocalContentStore`.\n ///\n /// - Parameters:\n /// - path: The path where content should be written under.\n public init(path: URL) throws {\n let ingestPath = path.appendingPathComponent(\"ingest\")\n let blobPath = path.appendingPathComponent(\"blobs/sha256\")\n\n let fileManager = FileManager.default\n try fileManager.createDirectory(at: ingestPath, withIntermediateDirectories: true)\n try fileManager.createDirectory(at: blobPath, withIntermediateDirectories: true)\n\n self._basePath = path\n self._ingestPath = ingestPath\n self._blobPath = blobPath\n self._lock = AsyncLock()\n Self.encoder.outputFormatting = .sortedKeys\n }\n\n /// Get a piece of content from the store. Returns nil if not\n /// found.\n ///\n /// - Parameters:\n /// - digest: The string digest of the content.\n public func get(digest: String) throws -> Content? {\n let d = digest.trimmingDigestPrefix\n let path = self._blobPath.appendingPathComponent(d)\n do {\n return try LocalContent(path: path)\n } catch let err as ContainerizationError {\n switch err.code {\n case .notFound:\n return nil\n default:\n throw err\n }\n }\n }\n\n /// Get a piece of content from the store and return the decoded version of\n /// it.\n ///\n /// - Parameters:\n /// - digest: The string digest of the content.\n public func get(digest: String) throws -> T? {\n guard let content: Content = try self.get(digest: digest) else {\n return nil\n }\n return try content.decode()\n }\n\n /// Delete all content besides a set provided.\n ///\n /// - Parameters:\n /// - keeping: The set of string digests to keep.\n public func delete(keeping: [String]) async throws -> ([String], UInt64) {\n let fileManager = FileManager.default\n let all = try fileManager.contentsOfDirectory(at: self._blobPath, includingPropertiesForKeys: nil)\n let allDigests = Set(all.map { $0.lastPathComponent })\n let toDelete = allDigests.subtracting(keeping)\n return try await self.delete(digests: Array(toDelete))\n }\n\n /// Delete a specific set of content.\n ///\n /// - Parameters:\n /// - digests: Array of strings denoting the digests of the content to delete.\n @discardableResult\n public func delete(digests: [String]) async throws -> ([String], UInt64) {\n let store = AsyncStore<([String], UInt64)>()\n try await self._lock.withLock { context in\n let fileManager = FileManager.default\n var deleted: [String] = []\n var deletedBytes: UInt64 = 0\n for toDelete in digests {\n let p = self._blobPath.appendingPathComponent(toDelete)\n guard let content = try? LocalContent(path: p) else {\n continue\n }\n deletedBytes += try content.size()\n try fileManager.removeItem(at: p)\n deleted.append(toDelete)\n }\n await store.set((deleted, deletedBytes))\n }\n return await store.get() ?? ([], 0)\n }\n\n /// Creates a transactional write to the content store.\n ///\n /// - Parameters:\n /// - body: Closure that is given a temporary `URL` of the base directory which all contents should be written to.\n /// This is a transaction write where any failed operation in the closure (caught exception) will result in all contents written\n /// in the closure to be deleted. If the closure succeeds, then all the content that have been written to the temporary `URL`\n /// will be moved into the actual blobs path of the content store.\n @discardableResult\n public func ingest(_ body: @Sendable @escaping (URL) async throws -> Void) async throws -> [String] {\n let (id, tempPath) = try await self.newIngestSession()\n try await body(tempPath)\n return try await self.completeIngestSession(id)\n }\n\n /// Creates a new ingest session and returns the session ID and temporary ingest directory corresponding to the session.\n /// The contents from the ingest directory are processed and moved into the content store once the session is marked complete.\n /// This can be done by invoking the `completeIngestSession` method with the returned session ID.\n public func newIngestSession() async throws -> (id: String, ingestDir: URL) {\n let id = UUID().uuidString\n let temporaryPath = self._ingestPath.appendingPathComponent(id)\n let fileManager = FileManager.default\n try fileManager.createDirectory(atPath: temporaryPath.path, withIntermediateDirectories: true)\n await self.activeIngestSessions.insert(id)\n return (id, temporaryPath)\n }\n\n /// Completes a previously started ingest session corresponding to `id`. The contents from the ingest\n /// directory from the session are moved into the content store atomically. Any failure encountered will\n /// result in a transaction failure causing none of the contents to be ingested into the store.\n /// - Parameters:\n /// - id: id of the ingest session to complete.\n @discardableResult\n public func completeIngestSession(_ id: String) async throws -> [String] {\n guard await activeIngestSessions.contains(id) else {\n throw ContainerizationError(.internalError, message: \"Invalid session id \\(id)\")\n }\n await activeIngestSessions.remove(id)\n let temporaryPath = self._ingestPath.appendingPathComponent(id)\n let fileManager = FileManager.default\n defer {\n try? fileManager.removeItem(at: temporaryPath)\n }\n let tempDigests: [URL] = try fileManager.contentsOfDirectory(at: temporaryPath, includingPropertiesForKeys: nil)\n return try await self._lock.withLock { context in\n var moved: [String] = []\n let fileManager = FileManager.default\n do {\n try tempDigests.forEach {\n let digest = $0.lastPathComponent\n let target = self._blobPath.appendingPathComponent(digest)\n // only ingest if not exists\n if !fileManager.fileExists(atPath: target.path) {\n try fileManager.moveItem(at: $0, to: target)\n moved.append(digest)\n }\n }\n } catch {\n moved.forEach {\n try? fileManager.removeItem(at: self._blobPath.appendingPathComponent($0))\n }\n throw error\n }\n return tempDigests.map { $0.lastPathComponent }\n }\n }\n\n /// Cancels a previously started ingest session corresponding to `id`.\n /// The contents from the ingest directory corresponding to the session are removed.\n /// - Parameters:\n /// - id: id of the ingest session to complete.\n public func cancelIngestSession(_ id: String) async throws {\n guard let _ = await self.activeIngestSessions.remove(id) else {\n return\n }\n let temporaryPath = self._ingestPath.appendingPathComponent(id)\n let fileManager = FileManager.default\n try? fileManager.removeItem(at: temporaryPath)\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/ManagedProcess.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport GRPC\nimport Logging\nimport Synchronization\n\nfinal class ManagedProcess: Sendable {\n let id: String\n\n private let log: Logger\n private let process: Command\n private let lock: Mutex\n private let syncfd: Pipe\n private let owningPid: Int32?\n\n private struct State {\n init(io: IO) {\n self.io = io\n }\n\n let io: IO\n var waiters: [CheckedContinuation] = []\n var exitStatus: Int32? = nil\n var pid: Int32 = 0\n }\n\n var pid: Int32 {\n self.lock.withLock {\n $0.pid\n }\n }\n\n // swiftlint: disable type_name\n protocol IO {\n func start(process: inout Command) throws\n func closeAfterExec() throws\n func resize(size: Terminal.Size) throws\n func closeStdin() throws\n }\n // swiftlint: enable type_name\n\n static func localizeLogger(log: inout Logger, id: String) {\n log[metadataKey: \"id\"] = \"\\(id)\"\n }\n\n init(\n id: String,\n stdio: HostStdio,\n bundle: ContainerizationOCI.Bundle,\n owningPid: Int32? = nil,\n log: Logger\n ) throws {\n self.id = id\n var log = log\n Self.localizeLogger(log: &log, id: id)\n self.log = log\n self.owningPid = owningPid\n\n let syncfd = Pipe()\n try syncfd.setCloexec()\n self.syncfd = syncfd\n\n let args: [String]\n if let owningPid {\n args = [\n \"exec\",\n \"--parent-pid\",\n \"\\(owningPid)\",\n \"--process-path\",\n bundle.getExecSpecPath(id: id).path,\n ]\n } else {\n args = [\"run\", \"--bundle-path\", bundle.path.path]\n }\n\n var process = Command(\n \"/sbin/vmexec\",\n arguments: args,\n extraFiles: [syncfd.fileHandleForWriting]\n )\n\n var io: IO\n if stdio.terminal {\n log.info(\"setting up terminal IO\")\n let attrs = Command.Attrs(setsid: false, setctty: false)\n process.attrs = attrs\n io = try TerminalIO(\n stdio: stdio,\n log: log\n )\n } else {\n process.attrs = .init(setsid: false)\n io = StandardIO(\n stdio: stdio,\n log: log\n )\n }\n\n log.info(\"starting io\")\n\n // Setup IO early. We expect the host to be listening already.\n try io.start(process: &process)\n\n self.process = process\n self.lock = Mutex(State(io: io))\n }\n}\n\nextension ManagedProcess {\n func start() throws -> Int32 {\n try self.lock.withLock {\n log.info(\n \"starting managed process\",\n metadata: [\n \"id\": \"\\(id)\"\n ])\n\n // Start the underlying process.\n try process.start()\n\n // Close our side of any pipes.\n try syncfd.fileHandleForWriting.close()\n try $0.io.closeAfterExec()\n\n guard let piddata = try syncfd.fileHandleForReading.readToEnd() else {\n throw ContainerizationError(.internalError, message: \"no pid data from sync pipe\")\n }\n\n let i = piddata.withUnsafeBytes { ptr in\n ptr.load(as: Int32.self)\n }\n\n log.info(\"got back pid data \\(i)\")\n $0.pid = i\n\n log.info(\n \"started managed process\",\n metadata: [\n \"pid\": \"\\(i)\",\n \"id\": \"\\(id)\",\n ])\n\n return i\n }\n }\n\n func setExit(_ status: Int32) {\n self.lock.withLock {\n self.log.info(\n \"managed process exit\",\n metadata: [\n \"status\": \"\\(status)\"\n ])\n\n $0.exitStatus = status\n\n for waiter in $0.waiters {\n waiter.resume(returning: status)\n }\n\n self.log.debug(\"\\($0.waiters.count) managed process waiters signaled\")\n $0.waiters.removeAll()\n }\n }\n\n /// Wait on the process to exit\n func wait() async -> Int32 {\n await withCheckedContinuation { cont in\n self.lock.withLock {\n if let status = $0.exitStatus {\n cont.resume(returning: status)\n return\n }\n $0.waiters.append(cont)\n }\n }\n }\n\n func kill(_ signal: Int32) throws {\n try self.lock.withLock {\n guard $0.exitStatus == nil else {\n return\n }\n\n self.log.info(\"sending signal \\(signal) to process \\($0.pid)\")\n guard Foundation.kill($0.pid, signal) == 0 else {\n throw POSIXError.fromErrno()\n }\n }\n }\n\n func resize(size: Terminal.Size) throws {\n try self.lock.withLock {\n guard $0.exitStatus == nil else {\n return\n }\n try $0.io.resize(size: size)\n }\n }\n\n func closeStdin() throws {\n try self.lock.withLock {\n try $0.io.closeStdin()\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationNetlink/NetlinkSession.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport ContainerizationOS\nimport Logging\n\n/// `NetlinkSession` facilitates interacting with netlink via a provided `NetlinkSocket`. This is the\n/// core high-level type offered to perform actions to the netlink surface in the kernel.\npublic struct NetlinkSession {\n private static let receiveDataLength = 65536\n private static let mtu: UInt32 = 1280\n private let socket: any NetlinkSocket\n private let log: Logger\n\n /// Creates a new `NetlinkSession`.\n /// - Parameters:\n /// - socket: The `NetlinkSocket` to use for netlink interaction.\n /// - log: The logger to use. The default value is `nil`.\n public init(socket: any NetlinkSocket, log: Logger? = nil) {\n self.socket = socket\n self.log = log ?? Logger(label: \"com.apple.containerization.netlink\")\n }\n\n /// Errors that may occur during netlink interaction.\n public enum Error: Swift.Error, CustomStringConvertible, Equatable {\n case invalidIpAddress\n case invalidPrefixLength\n case unexpectedInfo(type: UInt16)\n case unexpectedOffset(offset: Int, size: Int)\n case unexpectedResidualPackets\n case unexpectedResultSet(count: Int, expected: Int)\n\n /// The description of the errors.\n public var description: String {\n switch self {\n case .invalidIpAddress:\n return \"invalid IP address\"\n case .invalidPrefixLength:\n return \"invalid prefix length\"\n case .unexpectedInfo(let type):\n return \"unexpected response information, type = \\(type)\"\n case .unexpectedOffset(let offset, let size):\n return \"unexpected buffer state, offset = \\(offset), size = \\(size)\"\n case .unexpectedResidualPackets:\n return \"unexpected residual response packets\"\n case .unexpectedResultSet(let count, let expected):\n return \"unexpected result set size, count = \\(count), expected = \\(expected)\"\n }\n }\n }\n\n /// Performs a link set command on an interface.\n /// - Parameters:\n /// - interface: The name of the interface.\n /// - up: The value to set the interface state to.\n public func linkSet(interface: String, up: Bool, mtu: UInt32? = nil) throws {\n // ip link set dev [interface] [up|down]\n let interfaceIndex = try getInterfaceIndex(interface)\n // build the attribute only when mtu is supplied\n let attr: RTAttribute? =\n (mtu != nil)\n ? RTAttribute(\n len: UInt16(RTAttribute.size + MemoryLayout.size),\n type: LinkAttributeType.IFLA_MTU)\n : nil\n let requestSize = NetlinkMessageHeader.size + InterfaceInfo.size + (attr?.paddedLen ?? 0)\n var requestBuffer = [UInt8](repeating: 0, count: requestSize)\n var requestOffset = 0\n\n let requestHeader = NetlinkMessageHeader(\n len: UInt32(requestBuffer.count),\n type: NetlinkType.RTM_NEWLINK,\n flags: NetlinkFlags.NLM_F_REQUEST | NetlinkFlags.NLM_F_ACK,\n pid: socket.pid)\n requestOffset = try requestHeader.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let flags = up ? InterfaceFlags.IFF_UP : 0\n let requestInfo = InterfaceInfo(\n family: UInt8(AddressFamily.AF_PACKET),\n index: interfaceIndex,\n flags: flags,\n change: InterfaceFlags.DEFAULT_CHANGE)\n requestOffset = try requestInfo.appendBuffer(&requestBuffer, offset: requestOffset)\n\n if let attr = attr, let m = mtu {\n requestOffset = try attr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard\n let newRequestOffset =\n requestBuffer.copyIn(as: UInt32.self, value: m, offset: requestOffset)\n else {\n throw NetlinkDataError.sendMarshalFailure\n }\n requestOffset = newRequestOffset\n }\n\n guard requestOffset == requestSize else {\n throw Error.unexpectedOffset(offset: requestOffset, size: requestSize)\n }\n\n try sendRequest(buffer: &requestBuffer)\n let (infos, _) = try parseResponse(infoType: NetlinkType.RTM_NEWLINK) { InterfaceInfo() }\n guard infos.count == 0 else {\n throw Error.unexpectedResultSet(count: infos.count, expected: 0)\n }\n }\n\n /// Performs a link get command on an interface.\n /// Returns information about the interface.\n /// - Parameter interface: The name of the interface to query.\n public func linkGet(interface: String? = nil) throws -> [LinkResponse] {\n // ip link ip show\n let maskAttr = RTAttribute(\n len: UInt16(RTAttribute.size + MemoryLayout.size), type: LinkAttributeType.IFLA_EXT_MASK)\n let interfaceName = try interface.map { try getInterfaceName($0) }\n let interfaceNameAttr = interfaceName.map {\n RTAttribute(len: UInt16(RTAttribute.size + $0.count), type: LinkAttributeType.IFLA_EXT_IFNAME)\n }\n let requestSize =\n NetlinkMessageHeader.size + InterfaceInfo.size + maskAttr.paddedLen + (interfaceNameAttr?.paddedLen ?? 0)\n var requestBuffer = [UInt8](repeating: 0, count: requestSize)\n var requestOffset = 0\n\n let flags =\n interface != nil ? NetlinkFlags.NLM_F_REQUEST : (NetlinkFlags.NLM_F_REQUEST | NetlinkFlags.NLM_F_DUMP)\n let requestHeader = NetlinkMessageHeader(\n len: UInt32(requestBuffer.count),\n type: NetlinkType.RTM_GETLINK,\n flags: flags,\n pid: socket.pid)\n requestOffset = try requestHeader.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let requestInfo = InterfaceInfo(\n family: UInt8(AddressFamily.AF_PACKET),\n index: 0,\n flags: InterfaceFlags.IFF_UP,\n change: InterfaceFlags.DEFAULT_CHANGE)\n requestOffset = try requestInfo.appendBuffer(&requestBuffer, offset: requestOffset)\n\n requestOffset = try maskAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard\n var requestOffset = requestBuffer.copyIn(\n as: UInt32.self,\n value: LinkAttributeMaskFilter.RTEXT_FILTER_VF | LinkAttributeMaskFilter.RTEXT_FILTER_SKIP_STATS,\n offset: requestOffset)\n else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n if let interfaceNameAttr {\n if let interfaceName {\n requestOffset = try interfaceNameAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard let updatedRequestOffset = requestBuffer.copyIn(buffer: interfaceName, offset: requestOffset)\n else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n requestOffset = updatedRequestOffset\n }\n }\n\n guard requestOffset == requestSize else {\n throw Error.unexpectedOffset(offset: requestOffset, size: requestSize)\n }\n\n try sendRequest(buffer: &requestBuffer)\n let (infos, attrDataLists) = try parseResponse(infoType: NetlinkType.RTM_NEWLINK) { InterfaceInfo() }\n var linkResponses: [LinkResponse] = []\n for i in 0...size * ipAddressBytes.count\n let requestSize = NetlinkMessageHeader.size + AddressInfo.size + 2 * addressAttrSize\n var requestBuffer = [UInt8](repeating: 0, count: requestSize)\n var requestOffset = 0\n\n let header = NetlinkMessageHeader(\n len: UInt32(requestBuffer.count),\n type: NetlinkType.RTM_NEWADDR,\n flags: NetlinkFlags.NLM_F_REQUEST | NetlinkFlags.NLM_F_ACK | NetlinkFlags.NLM_F_EXCL\n | NetlinkFlags.NLM_F_CREATE,\n seq: 0,\n pid: socket.pid)\n requestOffset = try header.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let requestInfo = AddressInfo(\n family: UInt8(AddressFamily.AF_INET),\n prefixLength: parsed.prefix,\n flags: 0,\n scope: NetlinkScope.RT_SCOPE_UNIVERSE,\n index: UInt32(interfaceIndex))\n requestOffset = try requestInfo.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let ipLocalAttr = RTAttribute(len: UInt16(addressAttrSize), type: AddressAttributeType.IFA_LOCAL)\n requestOffset = try ipLocalAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard var requestOffset = requestBuffer.copyIn(buffer: ipAddressBytes, offset: requestOffset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n let ipAddressAttr = RTAttribute(len: UInt16(addressAttrSize), type: AddressAttributeType.IFA_ADDRESS)\n requestOffset = try ipAddressAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard let requestOffset = requestBuffer.copyIn(buffer: ipAddressBytes, offset: requestOffset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n guard requestOffset == requestSize else {\n throw Error.unexpectedOffset(offset: requestOffset, size: requestSize)\n }\n\n try sendRequest(buffer: &requestBuffer)\n let (infos, _) = try parseResponse(infoType: NetlinkType.RTM_NEWLINK) { AddressInfo() }\n guard infos.count == 0 else {\n throw Error.unexpectedResultSet(count: infos.count, expected: 0)\n }\n }\n\n private func parseCIDR(cidr: String) throws -> (address: String, prefix: UInt8) {\n let split = cidr.components(separatedBy: \"/\")\n guard split.count == 2 else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n let address = split[0]\n guard let prefixLength = PrefixLength(split[1]) else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n guard prefixLength >= 0 && prefixLength <= 32 else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n return (address, prefixLength)\n }\n\n /// Adds a route to an interface.\n /// - Parameters:\n /// - interface: The name of the interface.\n /// - destinationAddress: The destination address to route to.\n /// - srcAddr: The source address to route from.\n public func routeAdd(\n interface: String,\n destinationAddress: String,\n srcAddr: String\n ) throws {\n // ip route add [dest-cidr] dev [interface] src [src-addr] proto kernel\n let parsed = try parseCIDR(cidr: destinationAddress)\n let interfaceIndex = try getInterfaceIndex(interface)\n let dstAddrBytes = try IPv4Address(parsed.address).networkBytes\n let dstAddrAttrSize = RTAttribute.size + dstAddrBytes.count\n let srcAddrBytes = try IPv4Address(srcAddr).networkBytes\n let srcAddrAttrSize = RTAttribute.size + srcAddrBytes.count\n let interfaceAttrSize = RTAttribute.size + MemoryLayout.size\n let requestSize =\n NetlinkMessageHeader.size + RouteInfo.size + dstAddrAttrSize + srcAddrAttrSize + interfaceAttrSize\n var requestBuffer = [UInt8](repeating: 0, count: requestSize)\n var requestOffset = 0\n\n let header = NetlinkMessageHeader(\n len: UInt32(requestBuffer.count),\n type: NetlinkType.RTM_NEWROUTE,\n flags: NetlinkFlags.NLM_F_REQUEST | NetlinkFlags.NLM_F_ACK | NetlinkFlags.NLM_F_EXCL\n | NetlinkFlags.NLM_F_CREATE,\n pid: socket.pid)\n requestOffset = try header.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let requestInfo = RouteInfo(\n family: UInt8(AddressFamily.AF_INET),\n dstLen: parsed.prefix,\n srcLen: 0,\n tos: 0,\n table: RouteTable.MAIN,\n proto: RouteProtocol.KERNEL,\n scope: RouteScope.LINK,\n type: RouteType.UNICAST,\n flags: 0)\n requestOffset = try requestInfo.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let dstAddrAttr = RTAttribute(len: UInt16(dstAddrAttrSize), type: RouteAttributeType.DST)\n requestOffset = try dstAddrAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard var requestOffset = requestBuffer.copyIn(buffer: dstAddrBytes, offset: requestOffset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n let srcAddrAttr = RTAttribute(len: UInt16(dstAddrAttrSize), type: RouteAttributeType.PREFSRC)\n requestOffset = try srcAddrAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard var requestOffset = requestBuffer.copyIn(buffer: srcAddrBytes, offset: requestOffset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n let interfaceAttr = RTAttribute(len: UInt16(interfaceAttrSize), type: RouteAttributeType.OIF)\n requestOffset = try interfaceAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard\n let requestOffset = requestBuffer.copyIn(\n as: UInt32.self,\n value: UInt32(interfaceIndex),\n offset: requestOffset)\n else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n guard requestOffset == requestSize else {\n throw Error.unexpectedOffset(offset: requestOffset, size: requestSize)\n }\n\n try sendRequest(buffer: &requestBuffer)\n let (infos, _) = try parseResponse(infoType: NetlinkType.RTM_NEWLINK) { AddressInfo() }\n guard infos.count == 0 else {\n throw Error.unexpectedResultSet(count: infos.count, expected: 0)\n }\n }\n\n /// Adds a default route to an interface.\n /// - Parameters:\n /// - interface: The name of the interface.\n /// - gateway: The gateway address.\n public func routeAddDefault(\n interface: String,\n gateway: String\n ) throws {\n // ip route add default via [dst-address] src [src-address]\n let dstAddrBytes = try IPv4Address(gateway).networkBytes\n let dstAddrAttrSize = RTAttribute.size + dstAddrBytes.count\n\n let interfaceAttrSize = RTAttribute.size + MemoryLayout.size\n let interfaceIndex = try getInterfaceIndex(interface)\n let requestSize = NetlinkMessageHeader.size + RouteInfo.size + dstAddrAttrSize + interfaceAttrSize\n\n var requestBuffer = [UInt8](repeating: 0, count: requestSize)\n var requestOffset = 0\n\n let header = NetlinkMessageHeader(\n len: UInt32(requestBuffer.count),\n type: NetlinkType.RTM_NEWROUTE,\n flags: NetlinkFlags.NLM_F_REQUEST | NetlinkFlags.NLM_F_ACK | NetlinkFlags.NLM_F_EXCL\n | NetlinkFlags.NLM_F_CREATE,\n pid: socket.pid)\n requestOffset = try header.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let requestInfo = RouteInfo(\n family: UInt8(AddressFamily.AF_INET),\n dstLen: 0,\n srcLen: 0,\n tos: 0,\n table: RouteTable.MAIN,\n proto: RouteProtocol.BOOT,\n scope: RouteScope.UNIVERSE,\n type: RouteType.UNICAST,\n flags: 0)\n requestOffset = try requestInfo.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let dstAddrAttr = RTAttribute(len: UInt16(dstAddrAttrSize), type: RouteAttributeType.GATEWAY)\n requestOffset = try dstAddrAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard var requestOffset = requestBuffer.copyIn(buffer: dstAddrBytes, offset: requestOffset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n let interfaceAttr = RTAttribute(len: UInt16(interfaceAttrSize), type: RouteAttributeType.OIF)\n requestOffset = try interfaceAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard\n let requestOffset = requestBuffer.copyIn(\n as: UInt32.self,\n value: UInt32(interfaceIndex),\n offset: requestOffset)\n else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n guard requestOffset == requestSize else {\n throw Error.unexpectedOffset(offset: requestOffset, size: requestSize)\n }\n\n try sendRequest(buffer: &requestBuffer)\n let (infos, _) = try parseResponse(infoType: NetlinkType.RTM_NEWLINK) { AddressInfo() }\n guard infos.count == 0 else {\n throw Error.unexpectedResultSet(count: infos.count, expected: 0)\n }\n }\n\n private func getInterfaceName(_ interface: String) throws -> [UInt8] {\n guard let interfaceNameData = interface.data(using: .utf8) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n var interfaceName = [UInt8](interfaceNameData)\n interfaceName.append(0)\n\n while interfaceName.count % MemoryLayout.size != 0 {\n interfaceName.append(0)\n }\n\n return interfaceName\n }\n\n private func getInterfaceIndex(_ interface: String) throws -> Int32 {\n let linkResponses = try linkGet(interface: interface)\n guard linkResponses.count == 1 else {\n throw Error.unexpectedResultSet(count: linkResponses.count, expected: 1)\n }\n\n return linkResponses[0].interfaceIndex\n }\n\n private func sendRequest(buffer: inout [UInt8]) throws {\n log.trace(\"SEND-LENGTH: \\(buffer.count)\")\n log.trace(\"SEND-DUMP: \\(buffer[0.. ([UInt8], Int) {\n var buffer = [UInt8](repeating: 0, count: Self.receiveDataLength)\n let size = try socket.recv(buf: &buffer, len: Self.receiveDataLength, flags: 0)\n log.trace(\"RECV-LENGTH: \\(size)\")\n log.trace(\"RECV-DUMP: \\(buffer[0..(infoType: UInt16? = nil, _ infoProvider: () -> T) throws -> (\n [T], [[RTAttributeData]]\n ) {\n var infos: [T] = []\n var attrDataLists: [[RTAttributeData]] = []\n\n var moreResponses = false\n repeat {\n var (buffer, size) = try receiveResponse()\n let header: NetlinkMessageHeader\n var offset = 0\n\n (header, offset) = try parseHeader(buffer: &buffer, offset: offset)\n if let infoType {\n if header.type == infoType {\n log.trace(\n \"RECV-INFO-DUMP: dump = \\(buffer[offset.. (Int32, Int) {\n guard let errorPtr = buffer.bind(as: Int32.self, offset: offset) else {\n throw NetlinkDataError.recvUnmarshalFailure\n }\n\n let rc = errorPtr.pointee\n log.trace(\"RECV-ERR-CODE: \\(rc)\")\n\n return (rc, offset + MemoryLayout.size)\n }\n\n private func parseErrorResponse(buffer: inout [UInt8], offset: Int) throws -> Int {\n var (rc, offset) = try parseErrorCode(buffer: &buffer, offset: offset)\n log.trace(\n \"RECV-ERR-HEADER-DUMP: dump = \\(buffer[offset.. (NetlinkMessageHeader, Int) {\n log.trace(\"RECV-HEADER-DUMP: dump = \\(buffer[offset.. (\n [RTAttributeData], Int\n ) {\n var attrDatas: [RTAttributeData] = []\n var offset = offset\n var residualCount = residualCount\n log.trace(\"RECV-RESIDUAL: \\(residualCount)\")\n\n while residualCount > 0 {\n var attr = RTAttribute()\n log.trace(\" RECV-ATTR-DUMP: dump = \\(buffer[offset..= 0 {\n log.trace(\" RECV-ATTR-DATA-DUMP: dump = \\(buffer[offset.. ArchiveError) throws {\n guard self == ARCHIVE_OK else { throw error() }\n }\n fileprivate func checkOk(elseThrow error: (CInt) -> ArchiveError) throws {\n guard self == ARCHIVE_OK else { throw error(self) }\n }\n\n}\n\nextension ArchiveReader: Sequence {\n public func makeIterator() -> Iterator {\n Iterator(reader: self)\n }\n\n public struct Iterator: IteratorProtocol {\n var reader: ArchiveReader\n\n public mutating func next() -> (WriteEntry, Data)? {\n let entry = WriteEntry()\n let result = archive_read_next_header2(reader.underlying, entry.underlying)\n if result == ARCHIVE_EOF {\n return nil\n }\n let data = reader.readDataForEntry(entry)\n return (entry, data)\n }\n }\n\n internal func readDataForEntry(_ entry: WriteEntry) -> Data {\n let bufferSize = Int(Swift.min(entry.size ?? 4096, 4096))\n var entry = Data()\n var part = Data(count: bufferSize)\n while true {\n let c = part.withUnsafeMutableBytes { buffer in\n guard let baseAddress = buffer.baseAddress else {\n return 0\n }\n return archive_read_data(self.underlying, baseAddress, buffer.count)\n }\n guard c > 0 else { break }\n part.count = c\n entry.append(part)\n }\n return entry\n }\n}\n\nextension ArchiveReader {\n public convenience init(name: String, bundle: Data, tempDirectoryBaseName: String? = nil) throws {\n let baseName = tempDirectoryBaseName ?? \"Unarchiver\"\n let url = createTemporaryDirectory(baseName: baseName)!.appendingPathComponent(name)\n try bundle.write(to: url, options: .atomic)\n try self.init(format: .zip, filter: .none, file: url)\n }\n\n /// Extracts the contents of an archive to the provided directory.\n /// Currently only handles regular files and directories present in the archive.\n public func extractContents(to directory: URL) throws {\n let fm = FileManager.default\n var foundEntry = false\n for (entry, data) in self {\n guard let p = entry.path else { continue }\n foundEntry = true\n let type = entry.fileType\n let target = directory.appending(path: p)\n switch type {\n case .regular:\n try data.write(to: target, options: .atomic)\n case .directory:\n try fm.createDirectory(at: target, withIntermediateDirectories: true)\n case .symbolicLink:\n guard let symlinkTarget = entry.symlinkTarget, let linkTargetURL = URL(string: symlinkTarget, relativeTo: target) else {\n continue\n }\n try fm.createSymbolicLink(at: target, withDestinationURL: linkTargetURL)\n default:\n continue\n }\n chmod(target.path(), entry.permissions)\n if let owner = entry.owner, let group = entry.group {\n chown(target.path(), owner, group)\n }\n }\n guard foundEntry else {\n throw ArchiveError.failedToExtractArchive(\"No entries found in archive\")\n }\n }\n\n /// This method extracts a given file from the archive.\n /// This operation modifies the underlying file descriptor's position within the archive,\n /// meaning subsequent reads will start from a new location.\n /// To reset the underlying file descriptor to the beginning of the archive, close and\n /// reopen the archive.\n public func extractFile(path: String) throws -> (WriteEntry, Data) {\n let entry = WriteEntry()\n while archive_read_next_header2(self.underlying, entry.underlying) != ARCHIVE_EOF {\n guard let entryPath = entry.path else { continue }\n let trimCharSet = CharacterSet(charactersIn: \"./\")\n let trimmedEntry = entryPath.trimmingCharacters(in: trimCharSet)\n let trimmedRequired = path.trimmingCharacters(in: trimCharSet)\n guard trimmedEntry == trimmedRequired else { continue }\n let data = readDataForEntry(entry)\n return (entry, data)\n }\n throw ArchiveError.failedToExtractArchive(\" \\(path) not found in archive\")\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Mount/Mount.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n#if canImport(Musl)\nimport Musl\nprivate let _mount = Musl.mount\nprivate let _umount = Musl.umount2\n#elseif canImport(Glibc)\nimport Glibc\nprivate let _mount = Glibc.mount\nprivate let _umount = Glibc.umount2\n#endif\n\n// Mount package modeled closely from containerd's: https://github.com/containerd/containerd/tree/main/core/mount\n\n/// `Mount` models a Linux mount (although potentially could be used on other unix platforms), and\n/// provides a simple interface to mount what the type describes.\npublic struct Mount: Sendable {\n // Type specifies the host-specific of the mount.\n public var type: String\n // Source specifies where to mount from. Depending on the host system, this\n // can be a source path or device.\n public var source: String\n // Target specifies an optional subdirectory as a mountpoint.\n public var target: String\n // Options contains zero or more fstab-style mount options.\n public var options: [String]\n\n public init(type: String, source: String, target: String, options: [String]) {\n self.type = type\n self.source = source\n self.target = target\n self.options = options\n }\n}\n\nextension Mount {\n internal struct FlagBehavior {\n let clear: Bool\n let flag: Int32\n\n public init(_ clear: Bool, _ flag: Int32) {\n self.clear = clear\n self.flag = flag\n }\n }\n\n #if os(Linux)\n internal static let flagsDictionary: [String: FlagBehavior] = [\n \"async\": .init(true, MS_SYNCHRONOUS),\n \"atime\": .init(true, MS_NOATIME),\n \"bind\": .init(false, MS_BIND),\n \"defaults\": .init(false, 0),\n \"dev\": .init(true, MS_NODEV),\n \"diratime\": .init(true, MS_NODIRATIME),\n \"dirsync\": .init(false, MS_DIRSYNC),\n \"exec\": .init(true, MS_NOEXEC),\n \"mand\": .init(false, MS_MANDLOCK),\n \"noatime\": .init(false, MS_NOATIME),\n \"nodev\": .init(false, MS_NODEV),\n \"nodiratime\": .init(false, MS_NODIRATIME),\n \"noexec\": .init(false, MS_NOEXEC),\n \"nomand\": .init(true, MS_MANDLOCK),\n \"norelatime\": .init(true, MS_RELATIME),\n \"nostrictatime\": .init(true, MS_STRICTATIME),\n \"nosuid\": .init(false, MS_NOSUID),\n \"rbind\": .init(false, MS_BIND | MS_REC),\n \"relatime\": .init(false, MS_RELATIME),\n \"remount\": .init(false, MS_REMOUNT),\n \"ro\": .init(false, MS_RDONLY),\n \"rw\": .init(true, MS_RDONLY),\n \"strictatime\": .init(false, MS_STRICTATIME),\n \"suid\": .init(true, MS_NOSUID),\n \"sync\": .init(false, MS_SYNCHRONOUS),\n ]\n\n internal struct MountOptions {\n var flags: Int32\n var data: [String]\n\n public init(_ flags: Int32 = 0, data: [String] = []) {\n self.flags = flags\n self.data = data\n }\n }\n\n /// Whether the mount is read only.\n public var readOnly: Bool {\n for option in self.options {\n if option == \"ro\" {\n return true\n }\n }\n return false\n }\n\n /// Mount the mount relative to `root` with the current set of data in the object.\n /// Optionally provide `createWithPerms` to set the permissions for the directory that\n /// it will be mounted at.\n public func mount(root: String, createWithPerms: Int16? = nil) throws {\n var rootURL = URL(fileURLWithPath: root)\n rootURL = rootURL.resolvingSymlinksInPath()\n rootURL = rootURL.appendingPathComponent(self.target)\n try self.mountToTarget(target: rootURL.path, createWithPerms: createWithPerms)\n }\n\n /// Mount the mount with the current set of data in the object. Optionally\n /// provide `createWithPerms` to set the permissions for the directory that\n /// it will be mounted at.\n public func mount(createWithPerms: Int16? = nil) throws {\n try self.mountToTarget(target: self.target, createWithPerms: createWithPerms)\n }\n\n private func mountToTarget(target: String, createWithPerms: Int16?) throws {\n let pageSize = sysconf(_SC_PAGESIZE)\n\n let opts = parseMountOptions()\n let dataString = opts.data.joined(separator: \",\")\n if dataString.count > pageSize {\n throw Error.validation(\"data string exceeds page size (\\(dataString.count) > \\(pageSize))\")\n }\n\n let propagationTypes: Int32 = MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE\n\n // Ensure propagation type change flags aren't included in other calls.\n let originalFlags = opts.flags & ~(propagationTypes)\n\n let targetURL = URL(fileURLWithPath: self.target)\n let targetParent = targetURL.deletingLastPathComponent().path\n if let perms = createWithPerms {\n try mkdirAll(targetParent, perms)\n }\n try mkdirAll(target, 0o755)\n\n if opts.flags & MS_REMOUNT == 0 || !dataString.isEmpty {\n guard _mount(self.source, target, self.type, UInt(originalFlags), dataString) == 0 else {\n throw Error.errno(\n errno,\n \"failed initial mount source=\\(self.source) target=\\(target) type=\\(self.type) data=\\(dataString)\"\n )\n }\n }\n\n if opts.flags & propagationTypes != 0 {\n // Change the propagation type.\n let pflags = propagationTypes | MS_REC | MS_SILENT\n guard _mount(\"\", target, \"\", UInt(opts.flags & pflags), \"\") == 0 else {\n throw Error.errno(errno, \"failed propagation change mount\")\n }\n }\n\n let bindReadOnlyFlags = MS_BIND | MS_RDONLY\n if originalFlags & bindReadOnlyFlags == bindReadOnlyFlags {\n guard _mount(\"\", target, \"\", UInt(originalFlags | MS_REMOUNT), \"\") == 0 else {\n throw Error.errno(errno, \"failed bind mount\")\n }\n }\n }\n\n private func mkdirAll(_ name: String, _ perm: Int16) throws {\n try FileManager.default.createDirectory(\n atPath: name,\n withIntermediateDirectories: true,\n attributes: [.posixPermissions: perm]\n )\n }\n\n private func parseMountOptions() -> MountOptions {\n var mountOpts = MountOptions()\n for option in self.options {\n if let entry = Self.flagsDictionary[option], entry.flag != 0 {\n if entry.clear {\n mountOpts.flags &= ~entry.flag\n } else {\n mountOpts.flags |= entry.flag\n }\n } else {\n mountOpts.data.append(option)\n }\n }\n return mountOpts\n }\n\n /// `Mount` errors\n public enum Error: Swift.Error, CustomStringConvertible {\n case errno(Int32, String)\n case validation(String)\n\n public var description: String {\n switch self {\n case .errno(let errno, let message):\n return \"mount failed with errno \\(errno): \\(message)\"\n case .validation(let message):\n return \"failed during validation: \\(message)\"\n }\n }\n }\n #endif\n}\n"], ["/containerization/vminitd/Sources/vminitd/ManagedContainer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nactor ManagedContainer {\n let id: String\n let initProcess: ManagedProcess\n\n private let _log: Logger\n private let _bundle: ContainerizationOCI.Bundle\n private var _execs: [String: ManagedProcess] = [:]\n\n var pid: Int32 {\n self.initProcess.pid\n }\n\n init(\n id: String,\n stdio: HostStdio,\n spec: ContainerizationOCI.Spec,\n log: Logger\n ) throws {\n let bundle = try ContainerizationOCI.Bundle.create(\n path: Self.craftBundlePath(id: id),\n spec: spec\n )\n log.info(\"created bundle with spec \\(spec)\")\n\n let initProcess = try ManagedProcess(\n id: id,\n stdio: stdio,\n bundle: bundle,\n owningPid: nil,\n log: log\n )\n log.info(\"created managed init process\")\n\n self.initProcess = initProcess\n self.id = id\n self._bundle = bundle\n self._log = log\n }\n}\n\nextension ManagedContainer {\n private func ensureExecExists(_ id: String) throws {\n if self._execs[id] == nil {\n throw ContainerizationError(\n .invalidState,\n message: \"exec \\(id) does not exist in container \\(self.id)\"\n )\n }\n }\n\n func createExec(\n id: String,\n stdio: HostStdio,\n process: ContainerizationOCI.Process\n ) throws {\n // Write the process config to the bundle, and pass this on\n // over to ManagedProcess to deal with.\n try self._bundle.createExecSpec(\n id: id,\n process: process\n )\n let process = try ManagedProcess(\n id: id,\n stdio: stdio,\n bundle: self._bundle,\n owningPid: self.initProcess.pid,\n log: self._log\n )\n self._execs[id] = process\n }\n\n func start(execID: String) async throws -> Int32 {\n let proc = try self.getExecOrInit(execID: execID)\n return try await ProcessSupervisor.default.start(process: proc)\n }\n\n func wait(execID: String) async throws -> Int32 {\n let proc = try self.getExecOrInit(execID: execID)\n return await proc.wait()\n }\n\n func kill(execID: String, _ signal: Int32) throws {\n let proc = try self.getExecOrInit(execID: execID)\n try proc.kill(signal)\n }\n\n func resize(execID: String, size: Terminal.Size) throws {\n let proc = try self.getExecOrInit(execID: execID)\n try proc.resize(size: size)\n }\n\n func closeStdin(execID: String) throws {\n let proc = try self.getExecOrInit(execID: execID)\n try proc.closeStdin()\n }\n\n func deleteExec(id: String) throws {\n try ensureExecExists(id)\n do {\n try self._bundle.deleteExecSpec(id: id)\n } catch {\n self._log.error(\"failed to remove exec spec from filesystem: \\(error)\")\n }\n self._execs.removeValue(forKey: id)\n }\n\n func delete() throws {\n try self._bundle.delete()\n }\n\n func getExecOrInit(execID: String) throws -> ManagedProcess {\n if execID == self.id {\n return self.initProcess\n }\n guard let proc = self._execs[execID] else {\n throw ContainerizationError(\n .invalidState,\n message: \"exec \\(execID) does not exist in container \\(self.id)\"\n )\n }\n return proc\n }\n}\n\nextension ContainerizationOCI.Bundle {\n func createExecSpec(id: String, process: ContainerizationOCI.Process) throws {\n let specDir = self.path.appending(path: \"execs/\\(id)\")\n\n let fm = FileManager.default\n try fm.createDirectory(\n atPath: specDir.path,\n withIntermediateDirectories: true\n )\n\n let specData = try JSONEncoder().encode(process)\n let processConfigPath = specDir.appending(path: \"process.json\")\n try specData.write(to: processConfigPath)\n }\n\n func getExecSpecPath(id: String) -> URL {\n self.path.appending(path: \"execs/\\(id)/process.json\")\n }\n\n func deleteExecSpec(id: String) throws {\n let specDir = self.path.appending(path: \"execs/\\(id)\")\n\n let fm = FileManager.default\n try fm.removeItem(at: specDir)\n }\n}\n\nextension ManagedContainer {\n static func craftBundlePath(id: String) -> URL {\n URL(fileURLWithPath: \"/run/container\").appending(path: id)\n }\n}\n"], ["/containerization/vminitd/Sources/vmexec/RunCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerizationOCI\nimport Foundation\nimport LCShim\nimport Logging\nimport Musl\n\nstruct RunCommand: ParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"run\",\n abstract: \"Run a container\"\n )\n\n @Option(name: .long, help: \"path to an OCI bundle\")\n var bundlePath: String\n\n mutating func run() throws {\n LoggingSystem.bootstrap(App.standardError)\n let log = Logger(label: \"vmexec\")\n\n let bundle = try ContainerizationOCI.Bundle.load(path: URL(filePath: bundlePath))\n let ociSpec = try bundle.loadConfig()\n try execInNamespace(spec: ociSpec, log: log)\n }\n\n private func childRootSetup(rootfs: ContainerizationOCI.Root, mounts: [ContainerizationOCI.Mount], log: Logger) throws {\n // setup rootfs\n try prepareRoot(rootfs: rootfs.path)\n try mountRootfs(rootfs: rootfs.path, mounts: mounts)\n try setDevSymlinks(rootfs: rootfs.path)\n\n try pivotRoot(rootfs: rootfs.path)\n try reOpenDevNull()\n }\n\n private func execInNamespace(spec: ContainerizationOCI.Spec, log: Logger) throws {\n guard let process = spec.process else {\n fatalError(\"no process configuration found in runtime spec\")\n }\n guard let root = spec.root else {\n fatalError(\"no root found in runtime spec\")\n }\n\n let syncfd = FileHandle(fileDescriptor: 3)\n if fcntl(3, F_SETFD, FD_CLOEXEC) == -1 {\n throw App.Errno(stage: \"cloexec(syncfd)\")\n }\n\n guard unshare(CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWUTS) == 0 else {\n throw App.Errno(stage: \"unshare(pid|mnt|uts)\")\n }\n\n let childPipe = Pipe()\n try childPipe.setCloexec()\n let processID = fork()\n\n guard processID != -1 else {\n try? childPipe.fileHandleForReading.close()\n try? childPipe.fileHandleForWriting.close()\n try? syncfd.close()\n\n throw App.Errno(stage: \"fork\")\n }\n\n if processID == 0 { // child\n try childPipe.fileHandleForReading.close()\n try syncfd.close()\n\n guard unshare(CLONE_NEWCGROUP) == 0 else {\n throw App.Errno(stage: \"unshare(cgroup)\")\n }\n\n guard setsid() != -1 else {\n throw App.Errno(stage: \"setsid()\")\n }\n\n try childRootSetup(rootfs: root, mounts: spec.mounts, log: log)\n\n if !spec.hostname.isEmpty {\n let errCode = spec.hostname.withCString { ptr in\n Musl.sethostname(ptr, spec.hostname.count)\n }\n guard errCode == 0 else {\n throw App.Errno(stage: \"sethostname()\")\n }\n }\n\n // Apply O_CLOEXEC to all file descriptors except stdio.\n // This ensures that all unwanted fds we may have accidentally\n // inherited are marked close-on-exec so they stay out of the\n // container.\n try App.applyCloseExecOnFDs()\n\n try App.setRLimits(rlimits: process.rlimits)\n\n // Change stdio to be owned by the requested user.\n try App.fixStdioPerms(user: process.user)\n\n // Set uid, gid, and supplementary groups.\n try App.setPermissions(user: process.user)\n\n if process.terminal {\n guard ioctl(0, UInt(TIOCSCTTY), 0) != -1 else {\n throw App.Errno(stage: \"setctty()\")\n }\n }\n\n try App.exec(process: process)\n } else { // parent process\n try childPipe.fileHandleForWriting.close()\n\n // wait until the pipe is closed then carry on.\n _ = try childPipe.fileHandleForReading.readToEnd()\n try childPipe.fileHandleForReading.close()\n\n // send our child's pid to our parent before we exit.\n var childPid = processID\n let data = Data(bytes: &childPid, count: MemoryLayout.size(ofValue: childPid))\n\n try syncfd.write(contentsOf: data)\n try syncfd.close()\n }\n }\n\n private func mountRootfs(rootfs: String, mounts: [ContainerizationOCI.Mount]) throws {\n let containerMount = ContainerMount(rootfs: rootfs, mounts: mounts)\n try containerMount.mountToRootfs()\n try containerMount.configureConsole()\n }\n\n private func prepareRoot(rootfs: String) throws {\n guard mount(\"\", \"/\", \"\", UInt(MS_SLAVE | MS_REC), nil) == 0 else {\n throw App.Errno(stage: \"mount(slave|rec)\")\n }\n\n guard mount(rootfs, rootfs, \"bind\", UInt(MS_BIND | MS_REC), nil) == 0 else {\n throw App.Errno(stage: \"mount(bind|rec)\")\n }\n }\n\n private func setDevSymlinks(rootfs: String) throws {\n let links: [(src: String, dst: String)] = [\n (\"/proc/self/fd\", \"/dev/fd\"),\n (\"/proc/self/fd/0\", \"/dev/stdin\"),\n (\"/proc/self/fd/1\", \"/dev/stdout\"),\n (\"/proc/self/fd/2\", \"/dev/stderr\"),\n ]\n\n let rootfsURL = URL(fileURLWithPath: rootfs)\n for (src, dst) in links {\n let dest = rootfsURL.appendingPathComponent(dst)\n guard symlink(src, dest.path) == 0 else {\n if errno == EEXIST {\n continue\n }\n throw App.Errno(stage: \"symlink()\")\n }\n }\n }\n\n private func reOpenDevNull() throws {\n let file = open(\"/dev/null\", O_RDWR)\n guard file != -1 else {\n throw App.Errno(stage: \"open(/dev/null)\")\n }\n defer { close(file) }\n\n var devNullStat = stat()\n try withUnsafeMutablePointer(to: &devNullStat) { pointer in\n guard fstat(file, pointer) == 0 else {\n throw App.Errno(stage: \"fstat(/dev/null)\")\n }\n }\n\n for fd: Int32 in 0...2 {\n var fdStat = stat()\n try withUnsafeMutablePointer(to: &fdStat) { pointer in\n guard fstat(fd, pointer) == 0 else {\n throw App.Errno(stage: \"fstat(fd)\")\n }\n }\n\n if fdStat.st_rdev == devNullStat.st_rdev {\n guard dup3(file, fd, 0) != -1 else {\n throw App.Errno(stage: \"dup3(null)\")\n }\n }\n }\n }\n\n /// Pivots the rootfs of the calling process in the namespace to the provided\n /// rootfs in the argument.\n ///\n /// The pivot_root(\".\", \".\") and unmount old root approach is exactly the same\n /// as runc's pivot root implementation in:\n /// https://github.com/opencontainers/runc/blob/main/libcontainer/rootfs_linux.go\n private func pivotRoot(rootfs: String) throws {\n let oldRoot = open(\"/\", O_RDONLY | O_DIRECTORY)\n if oldRoot <= 0 {\n throw App.Errno(stage: \"open(oldroot)\")\n }\n defer { close(oldRoot) }\n\n let newRoot = open(rootfs, O_RDONLY | O_DIRECTORY)\n if newRoot <= 0 {\n throw App.Errno(stage: \"open(newroot)\")\n }\n\n defer { close(newRoot) }\n\n // change cwd to the new root\n guard fchdir(newRoot) == 0 else {\n throw App.Errno(stage: \"fchdir(newroot)\")\n }\n guard CZ_pivot_root(toCString(\".\"), toCString(\".\")) == 0 else {\n throw App.Errno(stage: \"pivot_root()\")\n }\n // change cwd to the old root\n guard fchdir(oldRoot) == 0 else {\n throw App.Errno(stage: \"fchdir(oldroot)\")\n }\n // mount old root rslave so that unmount doesn't propagate back to outside\n // the namespace\n guard mount(\"\", \".\", \"\", UInt(MS_SLAVE | MS_REC), nil) == 0 else {\n throw App.Errno(stage: \"mount(., slave|rec)\")\n }\n // unmount old root\n guard umount2(\".\", Int32(MNT_DETACH)) == 0 else {\n throw App.Errno(stage: \"umount(.)\")\n }\n // switch cwd to the new root\n guard chdir(\"/\") == 0 else {\n throw App.Errno(stage: \"chdir(/)\")\n }\n }\n\n private func toCString(_ str: String) -> UnsafeMutablePointer? {\n let cString = str.utf8CString\n let cStringCopy = UnsafeMutableBufferPointer.allocate(capacity: cString.count)\n _ = cStringCopy.initialize(from: cString)\n return UnsafeMutablePointer(cStringCopy.baseAddress)\n }\n}\n"], ["/containerization/Sources/Containerization/Mount.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport Virtualization\nimport ContainerizationError\n#endif\n\n/// A filesystem mount exposed to a container.\npublic struct Mount: Sendable {\n /// The filesystem or mount type. This is the string\n /// that will be used for the mount syscall itself.\n public var type: String\n /// The source path of the mount.\n public var source: String\n /// The destination path of the mount.\n public var destination: String\n /// Filesystem or mount specific options.\n public var options: [String]\n /// Runtime specific options. This can be used\n /// as a way to discern what kind of device a vmm\n /// should create for this specific mount (virtioblock\n /// virtiofs etc.).\n public let runtimeOptions: RuntimeOptions\n\n /// A type representing a \"hint\" of what type\n /// of mount this really is (block, directory, purely\n /// guest mount) and a set of type specific options, if any.\n public enum RuntimeOptions: Sendable {\n case virtioblk([String])\n case virtiofs([String])\n case any\n }\n\n init(\n type: String,\n source: String,\n destination: String,\n options: [String],\n runtimeOptions: RuntimeOptions\n ) {\n self.type = type\n self.source = source\n self.destination = destination\n self.options = options\n self.runtimeOptions = runtimeOptions\n }\n\n /// Mount representing a virtio block device.\n public static func block(\n format: String,\n source: String,\n destination: String,\n options: [String] = [],\n runtimeOptions: [String] = []\n ) -> Self {\n .init(\n type: format,\n source: source,\n destination: destination,\n options: options,\n runtimeOptions: .virtioblk(runtimeOptions)\n )\n }\n\n /// Mount representing a virtiofs share.\n public static func share(\n source: String,\n destination: String,\n options: [String] = [],\n runtimeOptions: [String] = []\n ) -> Self {\n .init(\n type: \"virtiofs\",\n source: source,\n destination: destination,\n options: options,\n runtimeOptions: .virtiofs(runtimeOptions)\n )\n }\n\n /// A generic mount.\n public static func any(\n type: String,\n source: String,\n destination: String,\n options: [String] = []\n ) -> Self {\n .init(\n type: type,\n source: source,\n destination: destination,\n options: options,\n runtimeOptions: .any\n )\n }\n\n #if os(macOS)\n /// Clone the Mount to the provided path.\n ///\n /// This uses `clonefile` to provide a copy-on-write copy of the Mount.\n public func clone(to: String) throws -> Self {\n let fm = FileManager.default\n let src = self.source\n try fm.copyItem(atPath: src, toPath: to)\n\n return .init(\n type: self.type,\n source: to,\n destination: self.destination,\n options: self.options,\n runtimeOptions: self.runtimeOptions\n )\n }\n #endif\n}\n\n#if os(macOS)\n\nextension Mount {\n func configure(config: inout VZVirtualMachineConfiguration) throws {\n switch self.runtimeOptions {\n case .virtioblk(let options):\n let device = try VZDiskImageStorageDeviceAttachment.mountToVZAttachment(mount: self, options: options)\n let attachment = VZVirtioBlockDeviceConfiguration(attachment: device)\n config.storageDevices.append(attachment)\n case .virtiofs(_):\n guard FileManager.default.fileExists(atPath: self.source) else {\n throw ContainerizationError(.notFound, message: \"directory \\(source) does not exist\")\n }\n\n let name = try hashMountSource(source: self.source)\n let urlSource = URL(fileURLWithPath: source)\n\n let device = VZVirtioFileSystemDeviceConfiguration(tag: name)\n device.share = VZSingleDirectoryShare(\n directory: VZSharedDirectory(\n url: urlSource,\n readOnly: readonly\n )\n )\n config.directorySharingDevices.append(device)\n case .any:\n break\n }\n }\n}\n\nextension VZDiskImageStorageDeviceAttachment {\n static func mountToVZAttachment(mount: Mount, options: [String]) throws -> VZDiskImageStorageDeviceAttachment {\n var cachingMode: VZDiskImageCachingMode = .automatic\n var synchronizationMode: VZDiskImageSynchronizationMode = .none\n\n for option in options {\n let split = option.split(separator: \"=\")\n if split.count != 2 {\n continue\n }\n\n let key = String(split[0])\n let value = String(split[1])\n\n switch key {\n case \"vzDiskImageCachingMode\":\n switch value {\n case \"automatic\":\n cachingMode = .automatic\n case \"cached\":\n cachingMode = .cached\n case \"uncached\":\n cachingMode = .uncached\n default:\n throw ContainerizationError(\n .invalidArgument,\n message: \"unknown vzDiskImageCachingMode value for virtio block device: \\(value)\"\n )\n }\n case \"vzDiskImageSynchronizationMode\":\n switch value {\n case \"full\":\n synchronizationMode = .full\n case \"fsync\":\n synchronizationMode = .fsync\n case \"none\":\n synchronizationMode = .none\n default:\n throw ContainerizationError(\n .invalidArgument,\n message: \"unknown vzDiskImageSynchronizationMode value for virtio block device: \\(value)\"\n )\n }\n default:\n throw ContainerizationError(\n .invalidArgument,\n message: \"unknown vmm option encountered: \\(key)\"\n )\n }\n }\n return try VZDiskImageStorageDeviceAttachment(\n url: URL(filePath: mount.source),\n readOnly: mount.readonly,\n cachingMode: cachingMode,\n synchronizationMode: synchronizationMode\n )\n }\n}\n\n#endif\n\nextension Mount {\n fileprivate var readonly: Bool {\n self.options.contains(\"ro\")\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Xattrs.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/*\n * Note: Both the entries and values for the attributes need to occupy a size that is a multiple of 4,\n * meaning, in cases where the attribute name or value is less than not a multiple of 4, it is padded with 0\n * until it reaches that size.\n */\n\nextension EXT4 {\n public struct ExtendedAttribute {\n public static let prefixMap: [Int: String] = [\n 1: \"user.\",\n 2: \"system.posix_acl_access\",\n 3: \"system.posix_acl_default\",\n 4: \"trusted.\",\n 6: \"security.\",\n 7: \"system.\",\n 8: \"system.richacl\",\n ]\n\n let name: String\n let index: UInt8\n let value: [UInt8]\n\n var sizeValue: UInt32 {\n UInt32((value.count + 3) & ~3)\n }\n\n var sizeEntry: UInt32 {\n UInt32((name.count + 3) & ~3 + 16) // 16 bytes are needed to store other metadata for the xattr entry\n }\n\n var size: UInt32 {\n sizeEntry + sizeValue\n }\n\n var fullName: String {\n Self.decompressName(id: Int(index), suffix: name)\n }\n\n var hash: UInt32 {\n var hash: UInt32 = 0\n for char in name {\n hash = (hash << 5) ^ (hash >> 27) ^ UInt32(char.asciiValue!)\n }\n var i = 0\n while i + 3 < value.count {\n let s = value[i..> 16) ^ v\n i += 4\n }\n if value.count % 4 != 0 {\n let last = value.count & ~3\n var buff: [UInt8] = [0, 0, 0, 0]\n for (i, byte) in value[last...].enumerated() {\n buff[i] = byte\n }\n let v = UInt32(littleEndian: buff.withUnsafeBytes { $0.load(as: UInt32.self) })\n hash = (hash << 16) ^ (hash >> 16) ^ v\n }\n return hash\n }\n\n init(name: String, value: [UInt8]) {\n let compressed = Self.compressName(name)\n self.name = compressed.str\n self.index = compressed.id\n self.value = value\n }\n\n init(idx: UInt8, compressedName name: String, value: [UInt8]) {\n self.name = name\n self.index = idx\n self.value = value\n }\n\n // MARK: Class methods\n public static func compressName(_ name: String) -> (id: UInt8, str: String) {\n for (id, prefix) in prefixMap.sorted(by: { $1.1.count < $0.1.count }) where name.hasPrefix(prefix) {\n return (UInt8(id), String(name.dropFirst(prefix.count)))\n }\n return (0, name)\n }\n\n public static func decompressName(id: Int, suffix: String) -> String {\n guard let prefix = prefixMap[id] else {\n return suffix\n }\n return \"\\(prefix)\\(suffix)\"\n }\n }\n\n public struct FileXattrsState {\n private let inodeCapacity: UInt32\n private let blockCapacity: UInt32\n private let inode: UInt32 // the inode number for which we are tracking these xattrs\n\n var inlineAttributes: [ExtendedAttribute] = []\n var blockAttributes: [ExtendedAttribute] = []\n private var usedSizeInline: UInt32 = 0\n private var usedSizeBlock: UInt32 = 0\n\n private var inodeFreeBytes: UInt32 {\n self.inodeCapacity - EXT4.XattrInodeHeaderSize - usedSizeInline - 4 // need to have 4 null bytes b/w xattr entries and values\n }\n\n private var blockFreeBytes: UInt32 {\n self.blockCapacity - EXT4.XattrBlockHeaderSize - usedSizeBlock - 4\n }\n\n init(inode: UInt32, inodeXattrCapacity: UInt32, blockCapacity: UInt32) {\n self.inode = inode\n self.inodeCapacity = inodeXattrCapacity\n self.blockCapacity = blockCapacity\n }\n\n public mutating func add(_ attribute: ExtendedAttribute) throws {\n let size = attribute.size\n if size <= inodeFreeBytes {\n usedSizeInline += size\n inlineAttributes.append(attribute)\n return\n }\n if size <= blockFreeBytes {\n usedSizeBlock += size\n blockAttributes.append(attribute)\n return\n }\n throw Error.insufficientSpace(Int(self.inode))\n }\n\n public func writeInlineAttributes(buffer: inout [UInt8]) throws {\n var idx = 0\n withUnsafeLittleEndianBytes(\n of: EXT4.XAttrHeaderMagic,\n body: { bytes in\n for byte in bytes {\n buffer[idx] = byte\n idx += 1\n }\n })\n try Self.write(buffer: &buffer, attrs: self.inlineAttributes, start: UInt16(idx), delta: 0, inline: true)\n }\n\n public func writeBlockAttributes(buffer: inout [UInt8]) throws {\n var idx = 0\n for val in [EXT4.XAttrHeaderMagic, 1, 1] {\n withUnsafeLittleEndianBytes(\n of: UInt32(val),\n body: { bytes in\n for byte in bytes {\n buffer[idx] = byte\n idx += 1\n }\n })\n }\n while idx != 32 {\n buffer[idx] = 0\n idx += 1\n }\n var attributes = self.blockAttributes\n attributes.sort(by: {\n if ($0.index < $1.index) || ($0.name.count < $1.name.count) || ($0.name < $1.name) {\n return true\n }\n return false\n })\n try Self.write(buffer: &buffer, attrs: attributes, start: UInt16(idx), delta: UInt16(idx), inline: false)\n }\n\n /// Writes the specified list of extended attribute entries and their values to the provided\n /// This method does not fill in any headers (Inode inline / block level) that may be required to parse these attributes\n ///\n /// - Parameters:\n /// - buffer: An array of [UInt8] where the data will be written into\n /// - attrs: The list of ExtendedAttributes to write\n /// - start: the index from where data should be put into the buffer - useful when if you dont want this method to be overwriting existing data\n /// - delta: index from where the begin the offset calculations\n /// - inline: if the byte buffer being written into is an inline data block for an inode: Determines the hash calculation\n private static func write(\n buffer: inout [UInt8], attrs: [ExtendedAttribute], start: UInt16, delta: UInt16, inline: Bool\n ) throws {\n var offset: UInt16 = UInt16(buffer.count) + delta - start\n var front = Int(start)\n var end = buffer.count\n\n for attribute in attrs {\n guard end - front >= 4 else {\n throw Error.malformedXattrBuffer\n }\n\n var out: [UInt8] = []\n let v = attribute.sizeValue\n offset -= UInt16(v)\n out.append(UInt8(attribute.name.count))\n out.append(attribute.index)\n withUnsafeLittleEndianBytes(\n of: UInt16(offset),\n body: { bytes in\n out.append(contentsOf: bytes)\n })\n out.append(contentsOf: [0, 0, 0, 0]) // these next four bytes indicate that the attr values are in the same block\n withUnsafeLittleEndianBytes(\n of: UInt32(attribute.value.count),\n body: { bytes in\n out.append(contentsOf: bytes)\n })\n if !inline {\n withUnsafeLittleEndianBytes(\n of: UInt32(attribute.hash),\n body: { bytes in\n out.append(contentsOf: bytes)\n })\n } else {\n out.append(contentsOf: [0, 0, 0, 0])\n }\n guard let name = attribute.name.data(using: .ascii) else {\n throw Error.convertAsciiString(attribute.name)\n }\n out.append(contentsOf: [UInt8](name))\n while out.count < Int(attribute.sizeEntry) { // ensure that xattr entry size is a multiple of 4\n out.append(0)\n }\n for (i, byte) in out.enumerated() {\n buffer[front + i] = byte\n }\n front += out.count\n\n end -= Int(attribute.sizeValue)\n for (i, byte) in attribute.value.enumerated() {\n buffer[end + i] = byte\n }\n }\n }\n\n public static func read(buffer: [UInt8], start: Int, offset: Int) throws -> [ExtendedAttribute] {\n var i = start\n var attribs: [ExtendedAttribute] = []\n // 16 is the size of 1 XAttrEntry\n while i + 16 < buffer.count {\n let attributeStart = i\n let rawXattrEntry = Array(buffer[i.. {\n AsyncStream { cont in\n self._stream.open()\n defer { self._stream.close() }\n\n let readBuffer = UnsafeMutablePointer.allocate(capacity: _buffSize)\n\n while true {\n let byteRead = self._stream.read(readBuffer, maxLength: _buffSize)\n if byteRead <= 0 {\n readBuffer.deallocate()\n cont.finish()\n break\n } else {\n let data = Data(bytes: readBuffer, count: byteRead)\n let buffer = ByteBuffer(bytes: data)\n cont.yield(buffer)\n }\n }\n }\n }\n\n /// Get access to an `AsyncStream` of `Data` objects from the input source.\n public var dataStream: AsyncStream {\n AsyncStream { cont in\n self._stream.open()\n defer { self._stream.close() }\n\n let readBuffer = UnsafeMutablePointer.allocate(capacity: self._buffSize)\n while true {\n let byteRead = self._stream.read(readBuffer, maxLength: self._buffSize)\n if byteRead <= 0 {\n readBuffer.deallocate()\n cont.finish()\n break\n } else {\n let data = Data(bytes: readBuffer, count: byteRead)\n cont.yield(data)\n }\n }\n }\n }\n}\n\nextension ReadStream {\n /// Errors that can be encountered while using a `ReadStream`.\n public enum Error: Swift.Error, CustomStringConvertible {\n case failedToCreateStream\n case noSuchFileOrDirectory(_ p: URL)\n\n public var description: String {\n switch self {\n case .failedToCreateStream:\n return \"failed to create stream\"\n case .noSuchFileOrDirectory(let p):\n return \"no such file or directory: \\(p.path)\"\n }\n }\n }\n}\n"], ["/containerization/vminitd/Sources/vmexec/ExecCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerizationOCI\nimport Foundation\nimport LCShim\nimport Logging\nimport Musl\n\nstruct ExecCommand: ParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"exec\",\n abstract: \"Exec in a container\"\n )\n\n @Option(name: .long, help: \"path to an OCI runtime spec process configuration\")\n var processPath: String\n\n @Option(name: .long, help: \"pid of the init process for the container\")\n var parentPid: Int\n\n func run() throws {\n LoggingSystem.bootstrap(App.standardError)\n let log = Logger(label: \"vmexec\")\n\n let src = URL(fileURLWithPath: processPath)\n let processBytes = try Data(contentsOf: src)\n let process = try JSONDecoder().decode(\n ContainerizationOCI.Process.self,\n from: processBytes\n )\n try execInNamespaces(process: process, log: log)\n }\n\n static func enterNS(path: String, nsType: Int32) throws {\n let fd = open(path, O_RDONLY)\n if fd <= 0 {\n throw App.Errno(stage: \"open(ns)\")\n }\n defer { close(fd) }\n\n guard setns(fd, nsType) == 0 else {\n throw App.Errno(stage: \"setns(fd)\")\n }\n }\n\n private func execInNamespaces(\n process: ContainerizationOCI.Process,\n log: Logger\n ) throws {\n // CLOEXEC the pipe fd that signals process readiness.\n let syncfd = FileHandle(fileDescriptor: 3)\n if fcntl(3, F_SETFD, FD_CLOEXEC) == -1 {\n throw App.Errno(stage: \"cloexec(syncfd)\")\n }\n\n try Self.enterNS(path: \"/proc/\\(self.parentPid)/ns/cgroup\", nsType: CLONE_NEWCGROUP)\n try Self.enterNS(path: \"/proc/\\(self.parentPid)/ns/pid\", nsType: CLONE_NEWPID)\n try Self.enterNS(path: \"/proc/\\(self.parentPid)/ns/uts\", nsType: CLONE_NEWUTS)\n try Self.enterNS(path: \"/proc/\\(self.parentPid)/ns/mnt\", nsType: CLONE_NEWNS)\n\n let childPipe = Pipe()\n try childPipe.setCloexec()\n let processID = fork()\n\n guard processID != -1 else {\n try? childPipe.fileHandleForReading.close()\n try? childPipe.fileHandleForWriting.close()\n try? syncfd.close()\n\n throw App.Errno(stage: \"fork\")\n }\n\n if processID == 0 { // child\n try childPipe.fileHandleForReading.close()\n try syncfd.close()\n\n guard setsid() != -1 else {\n throw App.Errno(stage: \"setsid()\")\n }\n\n // Apply O_CLOEXEC to all file descriptors except stdio.\n // This ensures that all unwanted fds we may have accidentally\n // inherited are marked close-on-exec so they stay out of the\n // container.\n try App.applyCloseExecOnFDs()\n try App.setRLimits(rlimits: process.rlimits)\n\n // Change stdio to be owned by the requested user.\n try App.fixStdioPerms(user: process.user)\n\n // Set uid, gid, and supplementary groups\n try App.setPermissions(user: process.user)\n\n if process.terminal {\n guard ioctl(0, UInt(TIOCSCTTY), 0) != -1 else {\n throw App.Errno(stage: \"setctty()\")\n }\n }\n\n try App.exec(process: process)\n } else { // parent process\n try childPipe.fileHandleForWriting.close()\n\n // wait until the pipe is closed then carry on.\n _ = try childPipe.fileHandleForReading.readToEnd()\n try childPipe.fileHandleForReading.close()\n\n // send our child's pid to our parent before we exit.\n var childPid = processID\n let data = Data(bytes: &childPid, count: MemoryLayout.size(ofValue: childPid))\n\n try syncfd.write(contentsOf: data)\n try syncfd.close()\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Command.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CShim\nimport Foundation\nimport Synchronization\n\n#if canImport(Darwin)\nimport Darwin\nprivate let _kill = Darwin.kill\n#elseif canImport(Musl)\nimport Musl\nprivate let _kill = Musl.kill\n#elseif canImport(Glibc)\nimport Glibc\nprivate let _kill = Glibc.kill\n#endif\n\n/// Use a command to run an executable.\npublic struct Command: Sendable {\n /// Path to the executable binary.\n public var executable: String\n /// Arguments provided to the binary.\n public var arguments: [String]\n /// Environment variables for the process.\n public var environment: [String]\n /// The directory where the process should execute.\n public var directory: String?\n /// Additional files to pass to the process.\n public var extraFiles: [FileHandle]\n /// The standard input.\n public var stdin: FileHandle?\n /// The standard output.\n public var stdout: FileHandle?\n /// The standard error.\n public var stderr: FileHandle?\n\n private let state: State\n\n /// System level attributes to set on the process.\n public struct Attrs: Sendable {\n /// Set pgroup for the new process.\n public var setPGroup: Bool\n /// Inherit the real uid/gid of the parent.\n public var resetIDs: Bool\n /// Reset the child's signal handlers to the default.\n public var setSignalDefault: Bool\n /// The initial signal mask for the process.\n public var signalMask: UInt32\n /// Create a new session for the process.\n public var setsid: Bool\n /// Set the controlling terminal for the process to fd 0.\n public var setctty: Bool\n /// Set the process user ID.\n public var uid: UInt32?\n /// Set the process group ID.\n public var gid: UInt32?\n\n public init(\n setPGroup: Bool = false,\n resetIDs: Bool = false,\n setSignalDefault: Bool = true,\n signalMask: UInt32 = 0,\n setsid: Bool = false,\n setctty: Bool = false,\n uid: UInt32? = nil,\n gid: UInt32? = nil\n ) {\n self.setPGroup = setPGroup\n self.resetIDs = resetIDs\n self.setSignalDefault = setSignalDefault\n self.signalMask = signalMask\n self.setsid = setsid\n self.setctty = setctty\n self.uid = uid\n self.gid = gid\n }\n }\n\n private final class State: Sendable {\n let pid: Atomic = Atomic(-1)\n }\n\n /// Attributes to set on the process.\n public var attrs = Attrs()\n\n /// System level process identifier.\n public var pid: Int32 { self.state.pid.load(ordering: .acquiring) }\n\n public init(\n _ executable: String,\n arguments: [String] = [],\n environment: [String] = environment(),\n directory: String? = nil,\n extraFiles: [FileHandle] = []\n ) {\n self.executable = executable\n self.arguments = arguments\n self.environment = environment\n self.extraFiles = extraFiles\n self.directory = directory\n self.state = State()\n }\n\n public static func environment() -> [String] {\n ProcessInfo.processInfo.environment\n .map { \"\\($0)=\\($1)\" }\n }\n}\n\nextension Command {\n public enum Error: Swift.Error, CustomStringConvertible {\n case processRunning\n\n public var description: String {\n switch self {\n case .processRunning:\n return \"the process is already running\"\n }\n }\n }\n}\n\nextension Command {\n @discardableResult\n public func kill(_ signal: Int32) -> Int32? {\n let pid = self.pid\n guard pid > 0 else {\n return nil\n }\n return _kill(pid, signal)\n }\n}\n\nextension Command {\n /// Start the process.\n public func start() throws {\n guard self.pid == -1 else {\n throw Error.processRunning\n }\n let child = try execute()\n self.state.pid.store(child, ordering: .releasing)\n }\n\n /// Wait for the process to exit and return the exit status.\n @discardableResult\n public func wait() throws -> Int32 {\n var rus = rusage()\n var ws = Int32()\n\n let pid = self.pid\n guard pid > 0 else {\n return -1\n }\n\n let result = wait4(pid, &ws, 0, &rus)\n guard result == pid else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n return Self.toExitStatus(ws)\n }\n\n private func execute() throws -> pid_t {\n var attrs = exec_command_attrs()\n exec_command_attrs_init(&attrs)\n\n let set = try createFileset()\n defer {\n try? set.null.close()\n }\n var fds = [Int32](repeating: 0, count: set.handles.count)\n for (i, handle) in set.handles.enumerated() {\n fds[i] = handle.fileDescriptor\n }\n\n attrs.setsid = self.attrs.setsid ? 1 : 0\n attrs.setctty = self.attrs.setctty ? 1 : 0\n attrs.setpgid = self.attrs.setPGroup ? 1 : 0\n\n var cwdPath: UnsafeMutablePointer?\n if let chdir = self.directory {\n cwdPath = strdup(chdir)\n }\n defer {\n if let cwdPath {\n free(cwdPath)\n }\n }\n\n if let uid = self.attrs.uid {\n attrs.uid = uid\n }\n if let gid = self.attrs.gid {\n attrs.gid = gid\n }\n\n var pid: pid_t = 0\n var argv = ([executable] + arguments).map { strdup($0) } + [nil]\n defer {\n for arg in argv where arg != nil {\n free(arg)\n }\n }\n\n let env = environment.map { strdup($0) } + [nil]\n defer {\n for e in env where e != nil {\n free(e)\n }\n }\n\n let result = fds.withUnsafeBufferPointer { file_handles in\n exec_command(\n &pid,\n argv[0],\n &argv,\n env,\n file_handles.baseAddress!, Int32(file_handles.count),\n cwdPath ?? nil,\n &attrs)\n }\n guard result == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n\n return pid\n }\n\n /// Create a posix_spawn file actions set of fds to pass to the new process\n private func createFileset() throws -> (null: FileHandle, handles: [FileHandle]) {\n // grab dev null incase a handle passed by the user is nil\n let null = try openDevNull()\n var files = [FileHandle]()\n files.append(stdin ?? null)\n files.append(stdout ?? null)\n files.append(stderr ?? null)\n files.append(contentsOf: extraFiles)\n return (null: null, handles: files)\n }\n\n /// Returns a file handle to /dev/null.\n private func openDevNull() throws -> FileHandle {\n let fd = open(\"/dev/null\", O_WRONLY, 0)\n guard fd > 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n return FileHandle(fileDescriptor: fd, closeOnDealloc: false)\n }\n}\n\nextension Command {\n private static let signalOffset: Int32 = 128\n\n private static let shift: Int32 = 8\n private static let mask: Int32 = 0x7F\n private static let stopped: Int32 = 0x7F\n private static let exited: Int32 = 0x00\n\n static func signaled(_ ws: Int32) -> Bool {\n ws & mask != stopped && ws & mask != exited\n }\n\n static func exited(_ ws: Int32) -> Bool {\n ws & mask == exited\n }\n\n static func exitStatus(_ ws: Int32) -> Int32 {\n let r: Int32\n #if os(Linux)\n r = ws >> shift & 0xFF\n #else\n r = ws >> shift\n #endif\n return r\n }\n\n public static func toExitStatus(_ ws: Int32) -> Int32 {\n if signaled(ws) {\n // We use the offset as that is how existing container\n // runtimes minic bash for the status when signaled.\n return Int32(Self.signalOffset + ws & mask)\n }\n if exited(ws) {\n return exitStatus(ws)\n }\n return ws\n }\n\n}\n\nprivate func WIFEXITED(_ status: Int32) -> Bool {\n _WSTATUS(status) == 0\n}\n\nprivate func _WSTATUS(_ status: Int32) -> Int32 {\n status & 0x7f\n}\n\nprivate func WIFSIGNALED(_ status: Int32) -> Bool {\n (_WSTATUS(status) != 0) && (_WSTATUS(status) != 0x7f)\n}\n\nprivate func WEXITSTATUS(_ status: Int32) -> Int32 {\n (status >> 8) & 0xff\n}\n\nprivate func WTERMSIG(_ status: Int32) -> Int32 {\n status & 0x7f\n}\n"], ["/containerization/Sources/Containerization/Image/ImageStore/ImageStore.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\n/// An ImageStore handles the mappings between an image's\n/// reference and the underlying descriptor inside of a content store.\npublic actor ImageStore: Sendable {\n /// The ImageStore path it was created with.\n public nonisolated let path: URL\n\n private let referenceManager: ReferenceManager\n internal let contentStore: ContentStore\n internal let lock: AsyncLock = AsyncLock()\n\n public init(path: URL, contentStore: ContentStore? = nil) throws {\n try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true)\n\n if let contentStore {\n self.contentStore = contentStore\n } else {\n self.contentStore = try LocalContentStore(path: path.appendingPathComponent(\"content\"))\n }\n\n self.path = path\n self.referenceManager = try ReferenceManager(path: path)\n }\n\n /// Return the default image store for the current user.\n public static let `default`: ImageStore = {\n do {\n let root = try defaultRoot()\n return try ImageStore(path: root)\n } catch {\n fatalError(\"unable to initialize default ImageStore \\(error)\")\n }\n }()\n\n private static func defaultRoot() throws -> URL {\n let root = FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first\n guard let root else {\n throw ContainerizationError(.notFound, message: \"unable to get Application Support directory for current user\")\n }\n return root.appendingPathComponent(\"com.apple.containerization\")\n\n }\n}\n\nextension ImageStore {\n /// Get an image from the `ImageStore`.\n ///\n /// - Parameters:\n /// - reference: Name of the image.\n /// - pull: Pull the image if it is not found.\n ///\n /// - Returns: A `Containerization.Image` object whose `reference` matches the given string.\n /// This method throws a `ContainerizationError(code: .notFound)` if the provided reference does not exist in the `ImageStore`.\n public func get(reference: String, pull: Bool = false) async throws -> Image {\n do {\n let desc = try await self.referenceManager.get(reference: reference)\n return Image(description: desc, contentStore: self.contentStore)\n } catch let error as ContainerizationError {\n if error.code == .notFound && pull {\n return try await self.pull(reference: reference)\n }\n throw error\n }\n }\n\n /// Get a list of all images in the `ImageStore`.\n ///\n /// - Returns: A `[Containerization.Image]` for all the images in the `ImageStore`.\n public func list() async throws -> [Image] {\n try await self.referenceManager.list().map { desc in\n Image(description: desc, contentStore: self.contentStore)\n }\n }\n\n /// Create a new image in the `ImageStore`.\n ///\n /// - Parameters:\n /// - description: The underlying `Image.Description` that contains information about the reference and index descriptor for the image to be created.\n ///\n /// - Note: It is assumed that the underlying manifests and blob layers for the image already exists in the `ContentStore` that the `ImageStore` was initialized with. This method is invoked when the `pull(...)` , `load(...)` and `tag(...)` methods are used.\n /// - Returns: A `Containerization.Image`\n @discardableResult\n internal func create(description: Image.Description) async throws -> Image {\n try await self.lock.withLock { ctx in\n try await self._create(description: description, lock: ctx)\n }\n }\n\n @discardableResult\n internal func _create(description: Image.Description, lock: AsyncLock.Context) async throws -> Image {\n try await self.referenceManager.create(description: description)\n return Image(description: description, contentStore: self.contentStore)\n }\n\n /// Delete an image from the `ImageStore`.\n ///\n /// - Parameters:\n /// - reference: Name of the image that is to be deleted.\n /// - performCleanup: Perform a garbage collection on the `ContentStore`, removing all unreferenced image layers and manifests,\n public func delete(reference: String, performCleanup: Bool = false) async throws {\n try await self.lock.withLock { lockCtx in\n try await self.referenceManager.delete(reference: reference)\n if performCleanup {\n try await self._prune(lockCtx)\n }\n }\n }\n\n /// Perform a garbage collection in the underlying `ContentStore` that is managed by the `ImageStore`.\n ///\n /// - Returns: Returns a tuple of `(deleted, freed)`.\n /// `deleted` : A list of the names of the content items that were deleted from the `ContentStore`,\n /// `freed` : The total size of the items that were deleted.\n @discardableResult\n public func prune() async throws -> (deleted: [String], freed: UInt64) {\n try await self.lock.withLock { lockCtx in\n try await self._prune(lockCtx)\n }\n }\n\n @discardableResult\n private func _prune(_ lock: AsyncLock.Context) async throws -> ([String], UInt64) {\n let images = try await self.list()\n var referenced: [String] = []\n for image in images {\n try await referenced.append(contentsOf: image.referencedDigests().uniqued())\n }\n let (deleted, size) = try await self.contentStore.delete(keeping: referenced)\n return (deleted, size)\n\n }\n\n /// Tag an existing image such that it can be referenced by another name.\n ///\n /// - Parameters:\n /// - existing: The reference to an image that already exists in the `ImageStore`.\n /// - new: The new reference by which the image should also be referenced as.\n /// - Note: The new image created in the `ImageStore` will have the same `Image.Description`\n /// as that of the image with reference `existing.`\n /// - Returns: A `Containerization.Image` object to the newly created image.\n public func tag(existing: String, new: String) async throws -> Image {\n let old = try await self.get(reference: existing)\n let descriptor = old.descriptor\n do {\n _ = try Reference.parse(new)\n } catch {\n throw ContainerizationError(.invalidArgument, message: \"Invalid reference \\(new). Error: \\(error)\")\n }\n let newDescription = Image.Description(reference: new, descriptor: descriptor)\n return try await self.create(description: newDescription)\n }\n}\n\nextension ImageStore {\n /// Pull an image and its associated manifest and blob layers from a remote registry.\n ///\n /// - Parameters:\n /// - reference: A string that references an image in a remote registry of the form `[:]/repository:`\n /// For example: \"docker.io/library/alpine:latest\".\n /// - platform: An optional parameter to indicate the platform to be pulled for the image.\n /// Defaults to `nil` signifying that layers for all supported platforms by the image will be pulled.\n /// - insecure: A boolean indicating if the connection to the remote registry should be made via plain-text http or not.\n /// Defaults to false, meaning the connection to the registry will be over https.\n /// - auth: An object that implements the `Authentication` protocol,\n /// used to add any credentials to the HTTP requests that are made to the registry.\n /// Defaults to `nil` meaning no additional credentials are added to any HTTP requests made to the registry.\n /// - progress: An optional handler over which progress update events about the pull operation can be received.\n ///\n /// - Returns: A `Containerization.Image` object to the newly pulled image.\n public func pull(\n reference: String, platform: Platform? = nil, insecure: Bool = false,\n auth: Authentication? = nil, progress: ProgressHandler? = nil\n ) async throws -> Image {\n\n let matcher = createPlatformMatcher(for: platform)\n let client = try RegistryClient(reference: reference, insecure: insecure, auth: auth)\n\n let ref = try Reference.parse(reference)\n let name = ref.path\n guard let tag = ref.tag ?? ref.digest else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid tag/digest for image reference \\(reference)\")\n }\n\n let rootDescriptor = try await client.resolve(name: name, tag: tag)\n let (id, tempDir) = try await self.contentStore.newIngestSession()\n let operation = ImportOperation(name: name, contentStore: self.contentStore, client: client, ingestDir: tempDir, progress: progress)\n do {\n let index = try await operation.import(root: rootDescriptor, matcher: matcher)\n return try await self.lock.withLock { lock in\n try await self.contentStore.completeIngestSession(id)\n let description = Image.Description(reference: reference, descriptor: index)\n let image = try await self._create(description: description, lock: lock)\n return image\n }\n } catch {\n try? await self.contentStore.cancelIngestSession(id)\n throw error\n }\n }\n\n /// Push an image and its associated manifest and blob layers to a remote registry.\n ///\n /// - Parameters:\n /// - reference: A string that references an image in the `ImageStore`. It must be of the form `[:]/repository:`\n /// For example: \"ghcr.io/foo-bar-baz/image:v1\".\n /// - platform: An optional parameter to indicate the platform to be pushed for the image.\n /// Defaults to `nil` signifying that layers for all supported platforms by the image will be pushed to the remote registry.\n /// - insecure: A boolean indicating if the connection to the remote registry should be made via plain-text http or not.\n /// Defaults to false, meaning the connection to the registry will be over https.\n /// - auth: An object that implements the `Authentication` protocol,\n /// used to add any credentials to the HTTP requests that are made to the registry.\n /// Defaults to `nil` meaning no additional credentials are added to any HTTP requests made to the registry.\n /// - progress: An optional handler over which progress update events about the push operation can be received.\n ///\n public func push(reference: String, platform: Platform? = nil, insecure: Bool = false, auth: Authentication? = nil, progress: ProgressHandler? = nil) async throws {\n let matcher = createPlatformMatcher(for: platform)\n let img = try await self.get(reference: reference)\n let allowedMediaTypes = [MediaTypes.dockerManifestList, MediaTypes.index]\n guard allowedMediaTypes.contains(img.mediaType) else {\n throw ContainerizationError(.internalError, message: \"Cannot push image \\(reference) with Index media type \\(img.mediaType)\")\n }\n let ref = try Reference.parse(reference)\n let name = ref.path\n guard let tag = ref.tag ?? ref.digest else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid tag/digest for image reference \\(reference)\")\n }\n let client = try RegistryClient(reference: reference, insecure: insecure, auth: auth)\n let operation = ExportOperation(name: name, tag: tag, contentStore: self.contentStore, client: client, progress: progress)\n try await operation.export(index: img.descriptor, platforms: matcher)\n }\n}\n\nextension ImageStore {\n /// Get the image for the init block from the image store.\n /// If the image does not exist locally, pull the image.\n public func getInitImage(reference: String, auth: Authentication? = nil, progress: ProgressHandler? = nil) async throws -> InitImage {\n do {\n let image = try await self.get(reference: reference)\n return InitImage(image: image)\n } catch let error as ContainerizationError {\n if error.code == .notFound {\n let image = try await self.pull(reference: reference, auth: auth, progress: progress)\n return InitImage(image: image)\n }\n throw error\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/RegistryClient+Push.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport NIO\n\nextension RegistryClient {\n /// Pushes the content specified by a descriptor to a remote registry.\n /// - Parameters:\n /// - name: The namespace which the descriptor should belong under.\n /// - tag: The tag or digest for uniquely identifying the manifest.\n /// By convention, any portion that may be a partial or whole digest\n /// will be proceeded by an `@`. Anything preceding the `@` will be referred\n /// to as \"tag\".\n /// This is usually broken down into the following possibilities:\n /// 1. \n /// 2. @\n /// 3. @\n /// The tag is anything except `@` and `:`, and digest is anything after the `@`\n /// - descriptor: The OCI descriptor of the content to be pushed.\n /// - streamGenerator: A closure that produces an`AsyncStream` of `ByteBuffer`\n /// for streaming data to the `HTTPClientRequest.Body`.\n /// The caller is responsible for providing the `AsyncStream` where the data may come from\n /// a file on disk, data in memory, etc.\n /// - progress: The progress handler to invoke as data is sent.\n public func push(\n name: String,\n ref tag: String,\n descriptor: Descriptor,\n streamGenerator: () throws -> T,\n progress: ProgressHandler?\n ) async throws where T.Element == ByteBuffer {\n var components = base\n\n let mediaType = descriptor.mediaType\n if mediaType.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Missing media type for descriptor \\(descriptor.digest)\")\n }\n\n var isManifest = false\n var existCheck: [String] = []\n\n switch mediaType {\n case MediaTypes.dockerManifest, MediaTypes.dockerManifestList, MediaTypes.imageManifest, MediaTypes.index:\n isManifest = true\n existCheck = self.getManifestPath(tag: tag, digest: descriptor.digest)\n default:\n existCheck = [\"blobs\", descriptor.digest]\n }\n\n // Check if the content already exists.\n components.path = \"/v2/\\(name)/\\(existCheck.joined(separator: \"/\"))\"\n\n let mediaTypes = [\n mediaType,\n \"*/*\",\n ]\n\n var headers = [\n (\"Accept\", mediaTypes.joined(separator: \", \"))\n ]\n\n try await request(components: components, method: .HEAD, headers: headers) { response in\n if response.status == .ok {\n var exists = false\n if isManifest && existCheck[1] != descriptor.digest {\n if descriptor.digest == response.headers.first(name: \"Docker-Content-Digest\") {\n exists = true\n }\n } else {\n exists = true\n }\n\n if exists {\n throw ContainerizationError(.exists, message: \"Content already exists \\(descriptor.digest)\")\n }\n } else if response.status != .notFound {\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n }\n\n if isManifest {\n let path = self.getManifestPath(tag: tag, digest: descriptor.digest)\n components.path = \"/v2/\\(name)/\\(path.joined(separator: \"/\"))\"\n headers = [\n (\"Content-Type\", mediaType)\n ]\n } else {\n // Start upload request for blobs.\n components.path = \"/v2/\\(name)/blobs/uploads/\"\n try await request(components: components, method: .POST) { response in\n switch response.status {\n case .ok, .accepted, .noContent:\n break\n case .created:\n throw ContainerizationError(.exists, message: \"Content already exists \\(descriptor.digest)\")\n default:\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n\n // Get the location to upload the blob.\n guard let location = response.headers.first(name: \"Location\") else {\n throw ContainerizationError(.invalidArgument, message: \"Missing required header Location\")\n }\n\n guard let urlComponents = URLComponents(string: location) else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid url \\(location)\")\n }\n var queryItems = urlComponents.queryItems ?? []\n queryItems.append(URLQueryItem(name: \"digest\", value: descriptor.digest))\n components.path = urlComponents.path\n components.queryItems = queryItems\n headers = [\n (\"Content-Type\", \"application/octet-stream\"),\n (\"Content-Length\", String(descriptor.size)),\n ]\n }\n }\n\n // We have to pass a body closure rather than a body to reset the stream when retrying.\n let bodyClosure = {\n let stream = try streamGenerator()\n let body = HTTPClientRequest.Body.stream(stream, length: .known(descriptor.size))\n return body\n }\n\n return try await request(components: components, method: .PUT, bodyClosure: bodyClosure, headers: headers) { response in\n switch response.status {\n case .ok, .created, .noContent:\n break\n default:\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n\n guard descriptor.digest == response.headers.first(name: \"Docker-Content-Digest\") else {\n let required = response.headers.first(name: \"Docker-Content-Digest\") ?? \"\"\n throw ContainerizationError(.internalError, message: \"Digest mismatch \\(descriptor.digest) != \\(required)\")\n }\n }\n }\n\n private func getManifestPath(tag: String, digest: String) -> [String] {\n var object = tag\n if let i = tag.firstIndex(of: \"@\") {\n let index = tag.index(after: i)\n if String(tag[index...]) != digest {\n object = \"\"\n } else {\n object = String(tag[...i])\n }\n }\n\n if object == \"\" {\n return [\"manifests\", digest]\n }\n\n return [\"manifests\", object]\n }\n}\n"], ["/containerization/Sources/cctl/KernelCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport Foundation\n\nextension Application {\n struct KernelCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"kernel\",\n abstract: \"Manage kernel images\",\n subcommands: [\n Create.self\n ]\n )\n\n struct Create: AsyncParsableCommand {\n @Option(name: .shortAndLong, help: \"Name for the kernel image\")\n var name: String\n\n @Option(name: .long, help: \"Labels to add to the built image of the form =, [=,...]\")\n var labels: [String] = []\n\n @Argument var kernels: [String]\n\n func run() async throws {\n let imageStore = Application.imageStore\n let contentStore = Application.contentStore\n let labels = Application.parseKeyValuePairs(from: labels)\n let binaries = try parseBinaries()\n _ = try await KernelImage.create(\n reference: name,\n binaries: binaries,\n labels: labels,\n imageStore: imageStore,\n contentStore: contentStore\n )\n }\n\n func parseBinaries() throws -> [Kernel] {\n var binaries = [Kernel]()\n for rawBinary in kernels {\n let parts = rawBinary.split(separator: \":\")\n guard parts.count == 2 else {\n throw \"Invalid binary format: \\(rawBinary)\"\n }\n let platform: SystemPlatform\n switch parts[1] {\n case \"arm64\":\n platform = .linuxArm\n case \"amd64\":\n platform = .linuxAmd\n default:\n fatalError(\"unsupported platform \\(parts[1])\")\n }\n binaries.append(\n .init(\n path: URL(fileURLWithPath: String(parts[0])),\n platform: platform\n )\n )\n }\n return binaries\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Terminal.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// `Terminal` provides a clean interface to deal with terminal interactions on Unix platforms.\npublic struct Terminal: Sendable {\n private let initState: termios?\n\n private var descriptor: Int32 {\n handle.fileDescriptor\n }\n public let handle: FileHandle\n\n public init(descriptor: Int32, setInitState: Bool = true) throws {\n if setInitState {\n self.initState = try Self.getattr(descriptor)\n } else {\n initState = nil\n }\n self.handle = .init(fileDescriptor: descriptor, closeOnDealloc: false)\n }\n\n /// Write the provided data to the tty device.\n public func write(_ data: Data) throws {\n try handle.write(contentsOf: data)\n }\n\n /// The winsize for a pty.\n public struct Size: Sendable {\n let size: winsize\n\n /// The width or `col` of the pty.\n public var width: UInt16 {\n size.ws_col\n }\n /// The height or `rows` of the pty.\n public var height: UInt16 {\n size.ws_row\n }\n\n init(_ size: winsize) {\n self.size = size\n }\n\n /// Set the size for use with a pty.\n public init(width cols: UInt16, height rows: UInt16) {\n self.size = winsize(ws_row: rows, ws_col: cols, ws_xpixel: 0, ws_ypixel: 0)\n }\n }\n\n /// Return the current pty attached to any of the STDIO descriptors.\n public static var current: Terminal {\n get throws {\n for i in [STDERR_FILENO, STDOUT_FILENO, STDIN_FILENO] {\n do {\n return try Terminal(descriptor: i)\n } catch {}\n }\n throw Error.notAPty\n }\n }\n\n /// The current window size for the pty.\n public var size: Size {\n get throws {\n var ws = winsize()\n try fromSyscall(ioctl(descriptor, UInt(TIOCGWINSZ), &ws))\n return Size(ws)\n }\n }\n\n /// Create a new pty pair.\n /// - Parameter initialSize: An initial size of the child pty.\n public static func create(initialSize: Size? = nil) throws -> (parent: Terminal, child: Terminal) {\n var parent: Int32 = 0\n var child: Int32 = 0\n let size = initialSize ?? Size(width: 120, height: 40)\n var ws = size.size\n\n try fromSyscall(openpty(&parent, &child, nil, nil, &ws))\n return (\n parent: try Terminal(descriptor: parent, setInitState: false),\n child: try Terminal(descriptor: child, setInitState: false)\n )\n }\n}\n\n// MARK: Errors\n\nextension Terminal {\n public enum Error: Swift.Error, CustomStringConvertible {\n case notAPty\n\n public var description: String {\n switch self {\n case .notAPty:\n return \"the provided fd is not a pty\"\n }\n }\n }\n}\n\nextension Terminal {\n /// Resize the current pty from the size of the provided pty.\n /// - Parameter pty: A pty to resize from.\n public func resize(from pty: Terminal) throws {\n var ws = try pty.size\n try fromSyscall(ioctl(descriptor, UInt(TIOCSWINSZ), &ws))\n }\n\n /// Resize the pty to the provided window size.\n /// - Parameter size: A window size for a pty.\n public func resize(size: Size) throws {\n var ws = size.size\n try fromSyscall(ioctl(descriptor, UInt(TIOCSWINSZ), &ws))\n }\n\n /// Resize the pty to the provided window size.\n /// - Parameter width: A width or cols of the terminal.\n /// - Parameter height: A height or rows of the terminal.\n public func resize(width: UInt16, height: UInt16) throws {\n var ws = Size(width: width, height: height)\n try fromSyscall(ioctl(descriptor, UInt(TIOCSWINSZ), &ws))\n }\n}\n\nextension Terminal {\n /// Enable raw mode for the pty.\n public func setraw() throws {\n var attr = try Self.getattr(descriptor)\n cfmakeraw(&attr)\n attr.c_oflag = attr.c_oflag | tcflag_t(OPOST)\n try fromSyscall(tcsetattr(descriptor, TCSANOW, &attr))\n }\n\n /// Enable echo support.\n /// Chars typed will be displayed to the terminal.\n public func enableEcho() throws {\n var attr = try Self.getattr(descriptor)\n attr.c_iflag &= ~tcflag_t(ICRNL)\n attr.c_lflag &= ~tcflag_t(ICANON | ECHO)\n try fromSyscall(tcsetattr(descriptor, TCSANOW, &attr))\n }\n\n /// Disable echo support.\n /// Chars typed will not be displayed back to the terminal.\n public func disableEcho() throws {\n var attr = try Self.getattr(descriptor)\n attr.c_lflag &= ~tcflag_t(ECHO)\n try fromSyscall(tcsetattr(descriptor, TCSANOW, &attr))\n }\n\n private static func getattr(_ fd: Int32) throws -> termios {\n var attr = termios()\n try fromSyscall(tcgetattr(fd, &attr))\n return attr\n }\n}\n\n// MARK: Reset\n\nextension Terminal {\n /// Close this pty's file descriptor.\n public func close() throws {\n do {\n // Use FileHandle's close directly as it sets the underlying fd in the object\n // to -1 for us.\n try self.handle.close()\n } catch {\n if let error = error as NSError?, error.domain == NSPOSIXErrorDomain {\n throw POSIXError(.init(rawValue: Int32(error.code))!)\n }\n throw error\n }\n }\n\n /// Reset the pty to its initial state.\n public func reset() throws {\n if var attr = initState {\n try fromSyscall(tcsetattr(descriptor, TCSANOW, &attr))\n }\n }\n\n /// Reset the pty to its initial state masking any errors.\n /// This is commonly used in a `defer` body to reset the current pty where the error code is not generally useful.\n public func tryReset() {\n try? reset()\n }\n}\n\nprivate func fromSyscall(_ status: Int32) throws {\n guard status == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/Application.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport NIOCore\nimport NIOPosix\n\n#if os(Linux)\nimport Musl\nimport LCShim\n#endif\n\n@main\nstruct Application {\n private static let foregroundEnvVar = \"FOREGROUND\"\n private static let vsockPort = 1024\n private static let standardErrorLock = NSLock()\n\n private static func runInForeground(_ log: Logger) throws {\n log.info(\"running vminitd under pid1\")\n\n var command = Command(\"/sbin/vminitd\")\n command.attrs = .init(setsid: true)\n command.stdin = .standardInput\n command.stdout = .standardOutput\n command.stderr = .standardError\n command.environment = [\"\\(foregroundEnvVar)=1\"]\n\n try command.start()\n _ = try command.wait()\n }\n\n private static func adjustLimits() throws {\n var limits = rlimit()\n guard getrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n limits.rlim_cur = 65536\n limits.rlim_max = 65536\n guard setrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n }\n\n @Sendable\n private static func standardError(label: String) -> StreamLogHandler {\n standardErrorLock.withLock {\n StreamLogHandler.standardError(label: label)\n }\n }\n\n static func main() async throws {\n LoggingSystem.bootstrap(standardError)\n var log = Logger(label: \"vminitd\")\n\n try adjustLimits()\n\n // when running under debug mode, launch vminitd as a sub process of pid1\n // so that we get a chance to collect better logs and errors before pid1 exists\n // and the kernel panics.\n #if DEBUG\n let environment = ProcessInfo.processInfo.environment\n let foreground = environment[Self.foregroundEnvVar]\n log.info(\"checking for shim var \\(foregroundEnvVar)=\\(String(describing: foreground))\")\n\n if foreground == nil {\n try runInForeground(log)\n exit(0)\n }\n\n // since we are not running as pid1 in this mode we must set ourselves\n // as a subpreaper so that all child processes are reaped by us and not\n // passed onto our parent.\n CZ_set_sub_reaper()\n #endif\n\n signal(SIGPIPE, SIG_IGN)\n\n // Because the sysctl rpc wouldn't make sense if this didn't always exist, we\n // ALWAYS mount /proc.\n guard Musl.mount(\"proc\", \"/proc\", \"proc\", 0, \"\") == 0 else {\n log.error(\"failed to mount /proc\")\n exit(1)\n }\n\n try Binfmt.mount()\n\n log.logLevel = .debug\n\n log.info(\"vminitd booting...\")\n let eg = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)\n let server = Initd(log: log, group: eg)\n\n do {\n log.info(\"serve vminitd api\")\n try await server.serve(port: vsockPort)\n log.info(\"vminitd api returned...\")\n } catch {\n log.error(\"vminitd boot error \\(error)\")\n exit(1)\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/User.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\n\n/// `User` provides utilities to ensure that a given username exists in\n/// /etc/passwd (and /etc/group).\npublic enum User {\n private static let passwdFile = \"/etc/passwd\"\n private static let groupFile = \"/etc/group\"\n\n public struct ExecUser: Sendable {\n public var uid: UInt32\n public var gid: UInt32\n public var sgids: [UInt32]\n public var home: String\n }\n\n private struct User {\n let name: String\n let password: String\n let uid: UInt32\n let gid: UInt32\n let gecos: String\n let home: String\n let shell: String\n\n /// The argument `rawString` must follow the below format.\n /// Name:Password:Uid:Gid:Gecos:Home:Shell\n init(rawString: String) throws {\n let args = rawString.split(separator: \":\", omittingEmptySubsequences: false)\n guard args.count == 7 else {\n throw ContainerizationError.init(.invalidArgument, message: \"Cannot parse User from '\\(rawString)'\")\n }\n guard let uid = UInt32(args[2]) else {\n throw ContainerizationError.init(.invalidArgument, message: \"Cannot parse uid from '\\(args[2])'\")\n }\n guard let gid = UInt32(args[3]) else {\n throw ContainerizationError.init(.invalidArgument, message: \"Cannot parse gid from '\\(args[3])'\")\n }\n self.name = String(args[0])\n self.password = String(args[1])\n self.uid = uid\n self.gid = gid\n self.gecos = String(args[4])\n self.home = String(args[5])\n self.shell = String(args[6])\n }\n }\n\n private struct Group {\n let name: String\n let password: String\n let gid: UInt32\n let users: [String]\n\n /// The argument `rawString` must follow the below format.\n /// Name:Password:Gid:user1,user2\n init(rawString: String) throws {\n let args = rawString.split(separator: \":\", omittingEmptySubsequences: false)\n guard args.count == 4 else {\n throw ContainerizationError.init(.invalidArgument, message: \"Cannot parse Group from '\\(rawString)'\")\n }\n guard let gid = UInt32(args[2]) else {\n throw ContainerizationError.init(.invalidArgument, message: \"Cannot parse gid from '\\(args[2])'\")\n }\n self.name = String(args[0])\n self.password = String(args[1])\n self.gid = gid\n self.users = args[3].split(separator: \",\").map { String($0) }\n }\n }\n}\n\n// MARK: Private methods\n\nextension User {\n /// Parse the contents of the passwd file\n private static func parsePasswd(passwdFile: URL) throws -> [User] {\n var users: [User] = []\n try self.parse(file: passwdFile) { line in\n let user = try User(rawString: line)\n users.append(user)\n }\n return users\n }\n\n /// Parse the contents of the group file\n private static func parseGroup(groupFile: URL) throws -> [Group] {\n var groups: [Group] = []\n try self.parse(file: groupFile) { line in\n let group = try Group(rawString: line)\n groups.append(group)\n }\n return groups\n }\n\n private static func parse(file: URL, handler: (_ line: String) throws -> Void) throws {\n let fm = FileManager.default\n guard fm.fileExists(atPath: file.absolutePath()) else {\n throw ContainerizationError(.notFound, message: \"File \\(file.absolutePath()) does not exist\")\n }\n let content = try String(contentsOf: file, encoding: .ascii)\n let lines = content.components(separatedBy: .newlines)\n for line in lines {\n guard !line.isEmpty else {\n continue\n }\n try handler(line.trimmingCharacters(in: .whitespaces))\n }\n }\n}\n\n// MARK: Public methods\n\nextension User {\n public static func parseUser(root: String, userString: String) throws -> ExecUser {\n let defaultUser = ExecUser(uid: 0, gid: 0, sgids: [], home: \"/\")\n guard !userString.isEmpty else {\n return defaultUser\n }\n\n let passwdPath = URL(filePath: root).appending(path: Self.passwdFile)\n let groupPath = URL(filePath: root).appending(path: Self.groupFile)\n let parts = userString.split(separator: \":\", maxSplits: 1, omittingEmptySubsequences: false)\n\n let userArg = String(parts[0])\n let userIdArg = Int(userArg)\n\n guard FileManager.default.fileExists(atPath: passwdPath.absolutePath()) else {\n guard let userIdArg else {\n throw ContainerizationError(.internalError, message: \"Cannot parse username \\(userArg)\")\n }\n let uid = UInt32(userIdArg)\n guard parts.count > 1 else {\n return ExecUser(uid: uid, gid: uid, sgids: [], home: \"/\")\n }\n guard let gid = UInt32(String(parts[1])) else {\n throw ContainerizationError(.internalError, message: \"Cannot parse user group from \\(userString)\")\n }\n return ExecUser(uid: uid, gid: gid, sgids: [], home: \"/\")\n }\n\n let registeredUsers = try parsePasswd(passwdFile: passwdPath)\n guard registeredUsers.count > 0 else {\n throw ContainerizationError(.internalError, message: \"No users configured in passwd file.\")\n }\n let matches = registeredUsers.filter { registeredUser in\n // Check for a match (either uid/name) against the configured users from the passwd file.\n // We have to check both the uid and the name cause we dont know the type of `userString`\n registeredUser.name == userArg || registeredUser.uid == (userIdArg ?? -1)\n }\n guard let match = matches.first else {\n // We did not find a matching uid/username in the passwd file\n throw ContainerizationError(.internalError, message: \"Cannot find User '\\(userArg)' in passwd file.\")\n }\n\n var user = ExecUser(uid: match.uid, gid: match.gid, sgids: [match.gid], home: match.home)\n\n guard !match.name.isEmpty else {\n return user\n }\n let matchedUser = match.name\n var groupArg = \"\"\n var groupIdArg: Int? = nil\n if parts.count > 1 {\n groupArg = String(parts[1])\n groupIdArg = Int(groupArg)\n }\n\n let registeredGroups: [Group] = {\n do {\n // Parse the /etc/group file for a list of registered groups.\n // If the file is missing / malformed, we bail out\n return try parseGroup(groupFile: groupPath)\n } catch {\n return []\n }\n }()\n guard registeredGroups.count > 0 else {\n return user\n }\n let matchingGroups = registeredGroups.filter { registeredGroup in\n if !groupArg.isEmpty {\n return registeredGroup.gid == (groupIdArg ?? -1) || registeredGroup.name == groupArg\n }\n return registeredGroup.users.contains(matchedUser) || registeredGroup.gid == match.gid\n }\n guard matchingGroups.count > 0 else {\n throw ContainerizationError(.internalError, message: \"Cannot find Group '\\(groupArg)' in groups file.\")\n }\n // We have found a list of groups that match the group specified in the argument `userString`.\n // Set the matched groups as the supplement groups for the user\n if !groupArg.isEmpty {\n // Reassign the user's group only we were explicitly asked for a group\n user.gid = matchingGroups.first!.gid\n user.sgids = matchingGroups.map { group in\n group.gid\n }\n } else {\n user.sgids.append(\n contentsOf: matchingGroups.map { group in\n group.gid\n })\n }\n return user\n }\n}\n"], ["/containerization/Sources/Containerization/VsockConnectionStream.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n#if os(macOS)\nimport Virtualization\n#endif\n\n/// A stream of vsock connections.\npublic final class VsockConnectionStream: NSObject, Sendable {\n /// A stream of connections dialed from the remote.\n public let connections: AsyncStream\n /// The port the connections are for.\n public let port: UInt32\n\n private let cont: AsyncStream.Continuation\n\n public init(port: UInt32) {\n self.port = port\n let (stream, continuation) = AsyncStream.makeStream(of: FileHandle.self)\n self.connections = stream\n self.cont = continuation\n }\n\n public func finish() {\n self.cont.finish()\n }\n}\n\n#if os(macOS)\n\nextension VsockConnectionStream: VZVirtioSocketListenerDelegate {\n public func listener(\n _: VZVirtioSocketListener, shouldAcceptNewConnection conn: VZVirtioSocketConnection,\n from _: VZVirtioSocketDevice\n ) -> Bool {\n let fd = dup(conn.fileDescriptor)\n conn.close()\n\n cont.yield(FileHandle(fileDescriptor: fd, closeOnDealloc: false))\n return true\n }\n}\n\n#endif\n"], ["/containerization/Sources/Containerization/SandboxContext/SandboxContext.grpc.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n// DO NOT EDIT.\n// swift-format-ignore-file\n//\n// Generated by the protocol buffer compiler.\n// Source: SandboxContext.proto\n//\nimport GRPC\nimport NIO\nimport NIOConcurrencyHelpers\nimport SwiftProtobuf\n\n\n/// Context for interacting with a container's runtime environment.\n///\n/// Usage: instantiate `Com_Apple_Containerization_Sandbox_V3_SandboxContextClient`, then call methods of this protocol to make API calls.\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextClientProtocol: GRPCClient {\n var serviceName: String { get }\n var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? { get }\n\n func mount(\n _ request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func umount(\n _ request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func setenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func getenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func mkdir(\n _ request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func sysctl(\n _ request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func setTime(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func setupEmulator(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func createProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func deleteProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func startProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func killProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func waitProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func resizeProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func closeProcessStdin(\n _ request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func proxyVsock(\n _ request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func stopVsockProxy(\n _ request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func ipLinkSet(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func ipAddrAdd(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func ipRouteAddLink(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func ipRouteAddDefault(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func configureDns(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func configureHosts(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func sync(\n _ request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func kill(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextClientProtocol {\n public var serviceName: String {\n return \"com.apple.containerization.sandbox.v3.SandboxContext\"\n }\n\n /// Mount a filesystem.\n ///\n /// - Parameters:\n /// - request: Request to send to Mount.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func mount(\n _ request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMountInterceptors() ?? []\n )\n }\n\n /// Unmount a filesystem.\n ///\n /// - Parameters:\n /// - request: Request to send to Umount.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func umount(\n _ request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.umount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeUmountInterceptors() ?? []\n )\n }\n\n /// Set an environment variable on the init process.\n ///\n /// - Parameters:\n /// - request: Request to send to Setenv.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func setenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetenvInterceptors() ?? []\n )\n }\n\n /// Get an environment variable from the init process.\n ///\n /// - Parameters:\n /// - request: Request to send to Getenv.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func getenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.getenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeGetenvInterceptors() ?? []\n )\n }\n\n /// Create a new directory inside the sandbox.\n ///\n /// - Parameters:\n /// - request: Request to send to Mkdir.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func mkdir(\n _ request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mkdir.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMkdirInterceptors() ?? []\n )\n }\n\n /// Set sysctls in the context of the sandbox.\n ///\n /// - Parameters:\n /// - request: Request to send to Sysctl.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func sysctl(\n _ request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sysctl.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSysctlInterceptors() ?? []\n )\n }\n\n /// Set time in the guest.\n ///\n /// - Parameters:\n /// - request: Request to send to SetTime.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func setTime(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setTime.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetTimeInterceptors() ?? []\n )\n }\n\n /// Set up an emulator in the guest for a specific binary format.\n ///\n /// - Parameters:\n /// - request: Request to send to SetupEmulator.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func setupEmulator(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setupEmulator.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetupEmulatorInterceptors() ?? []\n )\n }\n\n /// Create a new process inside the container.\n ///\n /// - Parameters:\n /// - request: Request to send to CreateProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func createProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.createProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateProcessInterceptors() ?? []\n )\n }\n\n /// Delete an existing process inside the container.\n ///\n /// - Parameters:\n /// - request: Request to send to DeleteProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func deleteProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.deleteProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeDeleteProcessInterceptors() ?? []\n )\n }\n\n /// Start the provided process.\n ///\n /// - Parameters:\n /// - request: Request to send to StartProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func startProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.startProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStartProcessInterceptors() ?? []\n )\n }\n\n /// Send a signal to the provided process.\n ///\n /// - Parameters:\n /// - request: Request to send to KillProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func killProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.killProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillProcessInterceptors() ?? []\n )\n }\n\n /// Wait for a process to exit and return the exit code.\n ///\n /// - Parameters:\n /// - request: Request to send to WaitProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func waitProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.waitProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeWaitProcessInterceptors() ?? []\n )\n }\n\n /// Resize the tty of a given process. This will error if the process does\n /// not have a pty allocated.\n ///\n /// - Parameters:\n /// - request: Request to send to ResizeProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func resizeProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.resizeProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeResizeProcessInterceptors() ?? []\n )\n }\n\n /// Close IO for a given process.\n ///\n /// - Parameters:\n /// - request: Request to send to CloseProcessStdin.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func closeProcessStdin(\n _ request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.closeProcessStdin.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCloseProcessStdinInterceptors() ?? []\n )\n }\n\n /// Proxy a vsock port to a unix domain socket in the guest, or vice versa.\n ///\n /// - Parameters:\n /// - request: Request to send to ProxyVsock.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func proxyVsock(\n _ request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.proxyVsock.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeProxyVsockInterceptors() ?? []\n )\n }\n\n /// Stop a vsock proxy to a unix domain socket.\n ///\n /// - Parameters:\n /// - request: Request to send to StopVsockProxy.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func stopVsockProxy(\n _ request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.stopVsockProxy.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStopVsockProxyInterceptors() ?? []\n )\n }\n\n /// Set the link state of a network interface.\n ///\n /// - Parameters:\n /// - request: Request to send to IpLinkSet.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func ipLinkSet(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipLinkSet.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpLinkSetInterceptors() ?? []\n )\n }\n\n /// Add an IPv4 address to a network interface.\n ///\n /// - Parameters:\n /// - request: Request to send to IpAddrAdd.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func ipAddrAdd(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipAddrAdd.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpAddrAddInterceptors() ?? []\n )\n }\n\n /// Add an IP route for a network interface.\n ///\n /// - Parameters:\n /// - request: Request to send to IpRouteAddLink.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func ipRouteAddLink(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddLink.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddLinkInterceptors() ?? []\n )\n }\n\n /// Add an IP route for a network interface.\n ///\n /// - Parameters:\n /// - request: Request to send to IpRouteAddDefault.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func ipRouteAddDefault(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddDefault.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddDefaultInterceptors() ?? []\n )\n }\n\n /// Configure DNS resolver.\n ///\n /// - Parameters:\n /// - request: Request to send to ConfigureDns.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func configureDns(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureDns.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureDnsInterceptors() ?? []\n )\n }\n\n /// Configure /etc/hosts.\n ///\n /// - Parameters:\n /// - request: Request to send to ConfigureHosts.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func configureHosts(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureHosts.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureHostsInterceptors() ?? []\n )\n }\n\n /// Perform the sync syscall.\n ///\n /// - Parameters:\n /// - request: Request to send to Sync.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func sync(\n _ request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sync.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSyncInterceptors() ?? []\n )\n }\n\n /// Send a signal to a process via the PID.\n ///\n /// - Parameters:\n /// - request: Request to send to Kill.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func kill(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.kill.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillInterceptors() ?? []\n )\n }\n}\n\n@available(*, deprecated)\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextClient: @unchecked Sendable {}\n\n@available(*, deprecated, renamed: \"Com_Apple_Containerization_Sandbox_V3_SandboxContextNIOClient\")\npublic final class Com_Apple_Containerization_Sandbox_V3_SandboxContextClient: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientProtocol {\n private let lock = Lock()\n private var _defaultCallOptions: CallOptions\n private var _interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol?\n public let channel: GRPCChannel\n public var defaultCallOptions: CallOptions {\n get { self.lock.withLock { return self._defaultCallOptions } }\n set { self.lock.withLockVoid { self._defaultCallOptions = newValue } }\n }\n public var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? {\n get { self.lock.withLock { return self._interceptors } }\n set { self.lock.withLockVoid { self._interceptors = newValue } }\n }\n\n /// Creates a client for the com.apple.containerization.sandbox.v3.SandboxContext service.\n ///\n /// - Parameters:\n /// - channel: `GRPCChannel` to the service host.\n /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them.\n /// - interceptors: A factory providing interceptors for each RPC.\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self._defaultCallOptions = defaultCallOptions\n self._interceptors = interceptors\n }\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SandboxContextNIOClient: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientProtocol {\n public var channel: GRPCChannel\n public var defaultCallOptions: CallOptions\n public var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol?\n\n /// Creates a client for the com.apple.containerization.sandbox.v3.SandboxContext service.\n ///\n /// - Parameters:\n /// - channel: `GRPCChannel` to the service host.\n /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them.\n /// - interceptors: A factory providing interceptors for each RPC.\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self.defaultCallOptions = defaultCallOptions\n self.interceptors = interceptors\n }\n}\n\n/// Context for interacting with a container's runtime environment.\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClientProtocol: GRPCClient {\n static var serviceDescriptor: GRPCServiceDescriptor { get }\n var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? { get }\n\n func makeMountCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeUmountCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeSetenvCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeGetenvCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeMkdirCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeSysctlCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeSetTimeCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeSetupEmulatorCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeCreateProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeDeleteProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeStartProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeKillProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeWaitProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeResizeProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeCloseProcessStdinCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeProxyVsockCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeStopVsockProxyCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeIpLinkSetCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeIpAddrAddCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeIpRouteAddLinkCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeIpRouteAddDefaultCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeConfigureDnsCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeConfigureHostsCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeSyncCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeKillCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClientProtocol {\n public static var serviceDescriptor: GRPCServiceDescriptor {\n return Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.serviceDescriptor\n }\n\n public var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? {\n return nil\n }\n\n public func makeMountCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMountInterceptors() ?? []\n )\n }\n\n public func makeUmountCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.umount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeUmountInterceptors() ?? []\n )\n }\n\n public func makeSetenvCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetenvInterceptors() ?? []\n )\n }\n\n public func makeGetenvCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.getenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeGetenvInterceptors() ?? []\n )\n }\n\n public func makeMkdirCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mkdir.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMkdirInterceptors() ?? []\n )\n }\n\n public func makeSysctlCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sysctl.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSysctlInterceptors() ?? []\n )\n }\n\n public func makeSetTimeCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setTime.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetTimeInterceptors() ?? []\n )\n }\n\n public func makeSetupEmulatorCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setupEmulator.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetupEmulatorInterceptors() ?? []\n )\n }\n\n public func makeCreateProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.createProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateProcessInterceptors() ?? []\n )\n }\n\n public func makeDeleteProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.deleteProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeDeleteProcessInterceptors() ?? []\n )\n }\n\n public func makeStartProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.startProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStartProcessInterceptors() ?? []\n )\n }\n\n public func makeKillProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.killProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillProcessInterceptors() ?? []\n )\n }\n\n public func makeWaitProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.waitProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeWaitProcessInterceptors() ?? []\n )\n }\n\n public func makeResizeProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.resizeProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeResizeProcessInterceptors() ?? []\n )\n }\n\n public func makeCloseProcessStdinCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.closeProcessStdin.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCloseProcessStdinInterceptors() ?? []\n )\n }\n\n public func makeProxyVsockCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.proxyVsock.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeProxyVsockInterceptors() ?? []\n )\n }\n\n public func makeStopVsockProxyCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.stopVsockProxy.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStopVsockProxyInterceptors() ?? []\n )\n }\n\n public func makeIpLinkSetCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipLinkSet.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpLinkSetInterceptors() ?? []\n )\n }\n\n public func makeIpAddrAddCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipAddrAdd.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpAddrAddInterceptors() ?? []\n )\n }\n\n public func makeIpRouteAddLinkCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddLink.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddLinkInterceptors() ?? []\n )\n }\n\n public func makeIpRouteAddDefaultCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddDefault.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddDefaultInterceptors() ?? []\n )\n }\n\n public func makeConfigureDnsCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureDns.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureDnsInterceptors() ?? []\n )\n }\n\n public func makeConfigureHostsCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureHosts.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureHostsInterceptors() ?? []\n )\n }\n\n public func makeSyncCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sync.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSyncInterceptors() ?? []\n )\n }\n\n public func makeKillCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.kill.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillInterceptors() ?? []\n )\n }\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClientProtocol {\n public func mount(\n _ request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_MountResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMountInterceptors() ?? []\n )\n }\n\n public func umount(\n _ request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_UmountResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.umount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeUmountInterceptors() ?? []\n )\n }\n\n public func setenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetenvResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetenvInterceptors() ?? []\n )\n }\n\n public func getenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_GetenvResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.getenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeGetenvInterceptors() ?? []\n )\n }\n\n public func mkdir(\n _ request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_MkdirResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mkdir.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMkdirInterceptors() ?? []\n )\n }\n\n public func sysctl(\n _ request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SysctlResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sysctl.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSysctlInterceptors() ?? []\n )\n }\n\n public func setTime(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetTimeResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setTime.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetTimeInterceptors() ?? []\n )\n }\n\n public func setupEmulator(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setupEmulator.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetupEmulatorInterceptors() ?? []\n )\n }\n\n public func createProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.createProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateProcessInterceptors() ?? []\n )\n }\n\n public func deleteProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.deleteProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeDeleteProcessInterceptors() ?? []\n )\n }\n\n public func startProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StartProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.startProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStartProcessInterceptors() ?? []\n )\n }\n\n public func killProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.killProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillProcessInterceptors() ?? []\n )\n }\n\n public func waitProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.waitProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeWaitProcessInterceptors() ?? []\n )\n }\n\n public func resizeProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.resizeProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeResizeProcessInterceptors() ?? []\n )\n }\n\n public func closeProcessStdin(\n _ request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.closeProcessStdin.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCloseProcessStdinInterceptors() ?? []\n )\n }\n\n public func proxyVsock(\n _ request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.proxyVsock.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeProxyVsockInterceptors() ?? []\n )\n }\n\n public func stopVsockProxy(\n _ request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.stopVsockProxy.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStopVsockProxyInterceptors() ?? []\n )\n }\n\n public func ipLinkSet(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipLinkSet.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpLinkSetInterceptors() ?? []\n )\n }\n\n public func ipAddrAdd(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipAddrAdd.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpAddrAddInterceptors() ?? []\n )\n }\n\n public func ipRouteAddLink(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddLink.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddLinkInterceptors() ?? []\n )\n }\n\n public func ipRouteAddDefault(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddDefault.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddDefaultInterceptors() ?? []\n )\n }\n\n public func configureDns(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureDns.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureDnsInterceptors() ?? []\n )\n }\n\n public func configureHosts(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureHosts.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureHostsInterceptors() ?? []\n )\n }\n\n public func sync(\n _ request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SyncResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sync.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSyncInterceptors() ?? []\n )\n }\n\n public func kill(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.kill.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillInterceptors() ?? []\n )\n }\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic struct Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClient: Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClientProtocol {\n public var channel: GRPCChannel\n public var defaultCallOptions: CallOptions\n public var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol?\n\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self.defaultCallOptions = defaultCallOptions\n self.interceptors = interceptors\n }\n}\n\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol: Sendable {\n\n /// - Returns: Interceptors to use when invoking 'mount'.\n func makeMountInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'umount'.\n func makeUmountInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'setenv'.\n func makeSetenvInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'getenv'.\n func makeGetenvInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'mkdir'.\n func makeMkdirInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'sysctl'.\n func makeSysctlInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'setTime'.\n func makeSetTimeInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'setupEmulator'.\n func makeSetupEmulatorInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'createProcess'.\n func makeCreateProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'deleteProcess'.\n func makeDeleteProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'startProcess'.\n func makeStartProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'killProcess'.\n func makeKillProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'waitProcess'.\n func makeWaitProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'resizeProcess'.\n func makeResizeProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'closeProcessStdin'.\n func makeCloseProcessStdinInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'proxyVsock'.\n func makeProxyVsockInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'stopVsockProxy'.\n func makeStopVsockProxyInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'ipLinkSet'.\n func makeIpLinkSetInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'ipAddrAdd'.\n func makeIpAddrAddInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'ipRouteAddLink'.\n func makeIpRouteAddLinkInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'ipRouteAddDefault'.\n func makeIpRouteAddDefaultInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'configureDns'.\n func makeConfigureDnsInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'configureHosts'.\n func makeConfigureHostsInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'sync'.\n func makeSyncInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'kill'.\n func makeKillInterceptors() -> [ClientInterceptor]\n}\n\npublic enum Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata {\n public static let serviceDescriptor = GRPCServiceDescriptor(\n name: \"SandboxContext\",\n fullName: \"com.apple.containerization.sandbox.v3.SandboxContext\",\n methods: [\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mount,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.umount,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setenv,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.getenv,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mkdir,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sysctl,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setTime,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setupEmulator,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.createProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.deleteProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.startProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.killProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.waitProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.resizeProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.closeProcessStdin,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.proxyVsock,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.stopVsockProxy,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipLinkSet,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipAddrAdd,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddLink,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddDefault,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureDns,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureHosts,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sync,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.kill,\n ]\n )\n\n public enum Methods {\n public static let mount = GRPCMethodDescriptor(\n name: \"Mount\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Mount\",\n type: GRPCCallType.unary\n )\n\n public static let umount = GRPCMethodDescriptor(\n name: \"Umount\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Umount\",\n type: GRPCCallType.unary\n )\n\n public static let setenv = GRPCMethodDescriptor(\n name: \"Setenv\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Setenv\",\n type: GRPCCallType.unary\n )\n\n public static let getenv = GRPCMethodDescriptor(\n name: \"Getenv\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Getenv\",\n type: GRPCCallType.unary\n )\n\n public static let mkdir = GRPCMethodDescriptor(\n name: \"Mkdir\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Mkdir\",\n type: GRPCCallType.unary\n )\n\n public static let sysctl = GRPCMethodDescriptor(\n name: \"Sysctl\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Sysctl\",\n type: GRPCCallType.unary\n )\n\n public static let setTime = GRPCMethodDescriptor(\n name: \"SetTime\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/SetTime\",\n type: GRPCCallType.unary\n )\n\n public static let setupEmulator = GRPCMethodDescriptor(\n name: \"SetupEmulator\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/SetupEmulator\",\n type: GRPCCallType.unary\n )\n\n public static let createProcess = GRPCMethodDescriptor(\n name: \"CreateProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/CreateProcess\",\n type: GRPCCallType.unary\n )\n\n public static let deleteProcess = GRPCMethodDescriptor(\n name: \"DeleteProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/DeleteProcess\",\n type: GRPCCallType.unary\n )\n\n public static let startProcess = GRPCMethodDescriptor(\n name: \"StartProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/StartProcess\",\n type: GRPCCallType.unary\n )\n\n public static let killProcess = GRPCMethodDescriptor(\n name: \"KillProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/KillProcess\",\n type: GRPCCallType.unary\n )\n\n public static let waitProcess = GRPCMethodDescriptor(\n name: \"WaitProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/WaitProcess\",\n type: GRPCCallType.unary\n )\n\n public static let resizeProcess = GRPCMethodDescriptor(\n name: \"ResizeProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ResizeProcess\",\n type: GRPCCallType.unary\n )\n\n public static let closeProcessStdin = GRPCMethodDescriptor(\n name: \"CloseProcessStdin\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/CloseProcessStdin\",\n type: GRPCCallType.unary\n )\n\n public static let proxyVsock = GRPCMethodDescriptor(\n name: \"ProxyVsock\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ProxyVsock\",\n type: GRPCCallType.unary\n )\n\n public static let stopVsockProxy = GRPCMethodDescriptor(\n name: \"StopVsockProxy\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/StopVsockProxy\",\n type: GRPCCallType.unary\n )\n\n public static let ipLinkSet = GRPCMethodDescriptor(\n name: \"IpLinkSet\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpLinkSet\",\n type: GRPCCallType.unary\n )\n\n public static let ipAddrAdd = GRPCMethodDescriptor(\n name: \"IpAddrAdd\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpAddrAdd\",\n type: GRPCCallType.unary\n )\n\n public static let ipRouteAddLink = GRPCMethodDescriptor(\n name: \"IpRouteAddLink\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpRouteAddLink\",\n type: GRPCCallType.unary\n )\n\n public static let ipRouteAddDefault = GRPCMethodDescriptor(\n name: \"IpRouteAddDefault\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpRouteAddDefault\",\n type: GRPCCallType.unary\n )\n\n public static let configureDns = GRPCMethodDescriptor(\n name: \"ConfigureDns\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ConfigureDns\",\n type: GRPCCallType.unary\n )\n\n public static let configureHosts = GRPCMethodDescriptor(\n name: \"ConfigureHosts\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ConfigureHosts\",\n type: GRPCCallType.unary\n )\n\n public static let sync = GRPCMethodDescriptor(\n name: \"Sync\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Sync\",\n type: GRPCCallType.unary\n )\n\n public static let kill = GRPCMethodDescriptor(\n name: \"Kill\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Kill\",\n type: GRPCCallType.unary\n )\n }\n}\n\n/// Context for interacting with a container's runtime environment.\n///\n/// To build a server, implement a class that conforms to this protocol.\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextProvider: CallHandlerProvider {\n var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextServerInterceptorFactoryProtocol? { get }\n\n /// Mount a filesystem.\n func mount(request: Com_Apple_Containerization_Sandbox_V3_MountRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Unmount a filesystem.\n func umount(request: Com_Apple_Containerization_Sandbox_V3_UmountRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Set an environment variable on the init process.\n func setenv(request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Get an environment variable from the init process.\n func getenv(request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Create a new directory inside the sandbox.\n func mkdir(request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Set sysctls in the context of the sandbox.\n func sysctl(request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Set time in the guest.\n func setTime(request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Set up an emulator in the guest for a specific binary format.\n func setupEmulator(request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Create a new process inside the container.\n func createProcess(request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Delete an existing process inside the container.\n func deleteProcess(request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Start the provided process.\n func startProcess(request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Send a signal to the provided process.\n func killProcess(request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Wait for a process to exit and return the exit code.\n func waitProcess(request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Resize the tty of a given process. This will error if the process does\n /// not have a pty allocated.\n func resizeProcess(request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Close IO for a given process.\n func closeProcessStdin(request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Proxy a vsock port to a unix domain socket in the guest, or vice versa.\n func proxyVsock(request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Stop a vsock proxy to a unix domain socket.\n func stopVsockProxy(request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Set the link state of a network interface.\n func ipLinkSet(request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Add an IPv4 address to a network interface.\n func ipAddrAdd(request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Add an IP route for a network interface.\n func ipRouteAddLink(request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Add an IP route for a network interface.\n func ipRouteAddDefault(request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Configure DNS resolver.\n func configureDns(request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Configure /etc/hosts.\n func configureHosts(request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Perform the sync syscall.\n func sync(request: Com_Apple_Containerization_Sandbox_V3_SyncRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Send a signal to a process via the PID.\n func kill(request: Com_Apple_Containerization_Sandbox_V3_KillRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextProvider {\n public var serviceName: Substring {\n return Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.serviceDescriptor.fullName[...]\n }\n\n /// Determines, calls and returns the appropriate request handler, depending on the request's method.\n /// Returns nil for methods not handled by this service.\n public func handle(\n method name: Substring,\n context: CallHandlerContext\n ) -> GRPCServerHandlerProtocol? {\n switch name {\n case \"Mount\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeMountInterceptors() ?? [],\n userFunction: self.mount(request:context:)\n )\n\n case \"Umount\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeUmountInterceptors() ?? [],\n userFunction: self.umount(request:context:)\n )\n\n case \"Setenv\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetenvInterceptors() ?? [],\n userFunction: self.setenv(request:context:)\n )\n\n case \"Getenv\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeGetenvInterceptors() ?? [],\n userFunction: self.getenv(request:context:)\n )\n\n case \"Mkdir\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeMkdirInterceptors() ?? [],\n userFunction: self.mkdir(request:context:)\n )\n\n case \"Sysctl\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSysctlInterceptors() ?? [],\n userFunction: self.sysctl(request:context:)\n )\n\n case \"SetTime\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetTimeInterceptors() ?? [],\n userFunction: self.setTime(request:context:)\n )\n\n case \"SetupEmulator\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetupEmulatorInterceptors() ?? [],\n userFunction: self.setupEmulator(request:context:)\n )\n\n case \"CreateProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCreateProcessInterceptors() ?? [],\n userFunction: self.createProcess(request:context:)\n )\n\n case \"DeleteProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeDeleteProcessInterceptors() ?? [],\n userFunction: self.deleteProcess(request:context:)\n )\n\n case \"StartProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeStartProcessInterceptors() ?? [],\n userFunction: self.startProcess(request:context:)\n )\n\n case \"KillProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeKillProcessInterceptors() ?? [],\n userFunction: self.killProcess(request:context:)\n )\n\n case \"WaitProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeWaitProcessInterceptors() ?? [],\n userFunction: self.waitProcess(request:context:)\n )\n\n case \"ResizeProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeResizeProcessInterceptors() ?? [],\n userFunction: self.resizeProcess(request:context:)\n )\n\n case \"CloseProcessStdin\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCloseProcessStdinInterceptors() ?? [],\n userFunction: self.closeProcessStdin(request:context:)\n )\n\n case \"ProxyVsock\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeProxyVsockInterceptors() ?? [],\n userFunction: self.proxyVsock(request:context:)\n )\n\n case \"StopVsockProxy\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeStopVsockProxyInterceptors() ?? [],\n userFunction: self.stopVsockProxy(request:context:)\n )\n\n case \"IpLinkSet\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpLinkSetInterceptors() ?? [],\n userFunction: self.ipLinkSet(request:context:)\n )\n\n case \"IpAddrAdd\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpAddrAddInterceptors() ?? [],\n userFunction: self.ipAddrAdd(request:context:)\n )\n\n case \"IpRouteAddLink\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpRouteAddLinkInterceptors() ?? [],\n userFunction: self.ipRouteAddLink(request:context:)\n )\n\n case \"IpRouteAddDefault\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpRouteAddDefaultInterceptors() ?? [],\n userFunction: self.ipRouteAddDefault(request:context:)\n )\n\n case \"ConfigureDns\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeConfigureDnsInterceptors() ?? [],\n userFunction: self.configureDns(request:context:)\n )\n\n case \"ConfigureHosts\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeConfigureHostsInterceptors() ?? [],\n userFunction: self.configureHosts(request:context:)\n )\n\n case \"Sync\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSyncInterceptors() ?? [],\n userFunction: self.sync(request:context:)\n )\n\n case \"Kill\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeKillInterceptors() ?? [],\n userFunction: self.kill(request:context:)\n )\n\n default:\n return nil\n }\n }\n}\n\n/// Context for interacting with a container's runtime environment.\n///\n/// To implement a server, implement an object which conforms to this protocol.\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncProvider: CallHandlerProvider, Sendable {\n static var serviceDescriptor: GRPCServiceDescriptor { get }\n var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextServerInterceptorFactoryProtocol? { get }\n\n /// Mount a filesystem.\n func mount(\n request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_MountResponse\n\n /// Unmount a filesystem.\n func umount(\n request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_UmountResponse\n\n /// Set an environment variable on the init process.\n func setenv(\n request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetenvResponse\n\n /// Get an environment variable from the init process.\n func getenv(\n request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_GetenvResponse\n\n /// Create a new directory inside the sandbox.\n func mkdir(\n request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_MkdirResponse\n\n /// Set sysctls in the context of the sandbox.\n func sysctl(\n request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SysctlResponse\n\n /// Set time in the guest.\n func setTime(\n request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetTimeResponse\n\n /// Set up an emulator in the guest for a specific binary format.\n func setupEmulator(\n request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse\n\n /// Create a new process inside the container.\n func createProcess(\n request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse\n\n /// Delete an existing process inside the container.\n func deleteProcess(\n request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse\n\n /// Start the provided process.\n func startProcess(\n request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StartProcessResponse\n\n /// Send a signal to the provided process.\n func killProcess(\n request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillProcessResponse\n\n /// Wait for a process to exit and return the exit code.\n func waitProcess(\n request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse\n\n /// Resize the tty of a given process. This will error if the process does\n /// not have a pty allocated.\n func resizeProcess(\n request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse\n\n /// Close IO for a given process.\n func closeProcessStdin(\n request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse\n\n /// Proxy a vsock port to a unix domain socket in the guest, or vice versa.\n func proxyVsock(\n request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse\n\n /// Stop a vsock proxy to a unix domain socket.\n func stopVsockProxy(\n request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse\n\n /// Set the link state of a network interface.\n func ipLinkSet(\n request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse\n\n /// Add an IPv4 address to a network interface.\n func ipAddrAdd(\n request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse\n\n /// Add an IP route for a network interface.\n func ipRouteAddLink(\n request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse\n\n /// Add an IP route for a network interface.\n func ipRouteAddDefault(\n request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse\n\n /// Configure DNS resolver.\n func configureDns(\n request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse\n\n /// Configure /etc/hosts.\n func configureHosts(\n request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse\n\n /// Perform the sync syscall.\n func sync(\n request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SyncResponse\n\n /// Send a signal to a process via the PID.\n func kill(\n request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillResponse\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncProvider {\n public static var serviceDescriptor: GRPCServiceDescriptor {\n return Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.serviceDescriptor\n }\n\n public var serviceName: Substring {\n return Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.serviceDescriptor.fullName[...]\n }\n\n public var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextServerInterceptorFactoryProtocol? {\n return nil\n }\n\n public func handle(\n method name: Substring,\n context: CallHandlerContext\n ) -> GRPCServerHandlerProtocol? {\n switch name {\n case \"Mount\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeMountInterceptors() ?? [],\n wrapping: { try await self.mount(request: $0, context: $1) }\n )\n\n case \"Umount\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeUmountInterceptors() ?? [],\n wrapping: { try await self.umount(request: $0, context: $1) }\n )\n\n case \"Setenv\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetenvInterceptors() ?? [],\n wrapping: { try await self.setenv(request: $0, context: $1) }\n )\n\n case \"Getenv\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeGetenvInterceptors() ?? [],\n wrapping: { try await self.getenv(request: $0, context: $1) }\n )\n\n case \"Mkdir\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeMkdirInterceptors() ?? [],\n wrapping: { try await self.mkdir(request: $0, context: $1) }\n )\n\n case \"Sysctl\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSysctlInterceptors() ?? [],\n wrapping: { try await self.sysctl(request: $0, context: $1) }\n )\n\n case \"SetTime\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetTimeInterceptors() ?? [],\n wrapping: { try await self.setTime(request: $0, context: $1) }\n )\n\n case \"SetupEmulator\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetupEmulatorInterceptors() ?? [],\n wrapping: { try await self.setupEmulator(request: $0, context: $1) }\n )\n\n case \"CreateProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCreateProcessInterceptors() ?? [],\n wrapping: { try await self.createProcess(request: $0, context: $1) }\n )\n\n case \"DeleteProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeDeleteProcessInterceptors() ?? [],\n wrapping: { try await self.deleteProcess(request: $0, context: $1) }\n )\n\n case \"StartProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeStartProcessInterceptors() ?? [],\n wrapping: { try await self.startProcess(request: $0, context: $1) }\n )\n\n case \"KillProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeKillProcessInterceptors() ?? [],\n wrapping: { try await self.killProcess(request: $0, context: $1) }\n )\n\n case \"WaitProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeWaitProcessInterceptors() ?? [],\n wrapping: { try await self.waitProcess(request: $0, context: $1) }\n )\n\n case \"ResizeProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeResizeProcessInterceptors() ?? [],\n wrapping: { try await self.resizeProcess(request: $0, context: $1) }\n )\n\n case \"CloseProcessStdin\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCloseProcessStdinInterceptors() ?? [],\n wrapping: { try await self.closeProcessStdin(request: $0, context: $1) }\n )\n\n case \"ProxyVsock\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeProxyVsockInterceptors() ?? [],\n wrapping: { try await self.proxyVsock(request: $0, context: $1) }\n )\n\n case \"StopVsockProxy\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeStopVsockProxyInterceptors() ?? [],\n wrapping: { try await self.stopVsockProxy(request: $0, context: $1) }\n )\n\n case \"IpLinkSet\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpLinkSetInterceptors() ?? [],\n wrapping: { try await self.ipLinkSet(request: $0, context: $1) }\n )\n\n case \"IpAddrAdd\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpAddrAddInterceptors() ?? [],\n wrapping: { try await self.ipAddrAdd(request: $0, context: $1) }\n )\n\n case \"IpRouteAddLink\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpRouteAddLinkInterceptors() ?? [],\n wrapping: { try await self.ipRouteAddLink(request: $0, context: $1) }\n )\n\n case \"IpRouteAddDefault\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpRouteAddDefaultInterceptors() ?? [],\n wrapping: { try await self.ipRouteAddDefault(request: $0, context: $1) }\n )\n\n case \"ConfigureDns\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeConfigureDnsInterceptors() ?? [],\n wrapping: { try await self.configureDns(request: $0, context: $1) }\n )\n\n case \"ConfigureHosts\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeConfigureHostsInterceptors() ?? [],\n wrapping: { try await self.configureHosts(request: $0, context: $1) }\n )\n\n case \"Sync\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSyncInterceptors() ?? [],\n wrapping: { try await self.sync(request: $0, context: $1) }\n )\n\n case \"Kill\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeKillInterceptors() ?? [],\n wrapping: { try await self.kill(request: $0, context: $1) }\n )\n\n default:\n return nil\n }\n }\n}\n\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextServerInterceptorFactoryProtocol: Sendable {\n\n /// - Returns: Interceptors to use when handling 'mount'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeMountInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'umount'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeUmountInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'setenv'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeSetenvInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'getenv'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeGetenvInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'mkdir'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeMkdirInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'sysctl'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeSysctlInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'setTime'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeSetTimeInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'setupEmulator'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeSetupEmulatorInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'createProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeCreateProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'deleteProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeDeleteProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'startProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeStartProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'killProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeKillProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'waitProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeWaitProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'resizeProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeResizeProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'closeProcessStdin'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeCloseProcessStdinInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'proxyVsock'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeProxyVsockInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'stopVsockProxy'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeStopVsockProxyInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'ipLinkSet'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeIpLinkSetInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'ipAddrAdd'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeIpAddrAddInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'ipRouteAddLink'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeIpRouteAddLinkInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'ipRouteAddDefault'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeIpRouteAddDefaultInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'configureDns'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeConfigureDnsInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'configureHosts'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeConfigureHostsInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'sync'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeSyncInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'kill'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeKillInterceptors() -> [ServerInterceptor]\n}\n\npublic enum Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata {\n public static let serviceDescriptor = GRPCServiceDescriptor(\n name: \"SandboxContext\",\n fullName: \"com.apple.containerization.sandbox.v3.SandboxContext\",\n methods: [\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.mount,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.umount,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.setenv,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.getenv,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.mkdir,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.sysctl,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.setTime,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.setupEmulator,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.createProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.deleteProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.startProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.killProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.waitProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.resizeProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.closeProcessStdin,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.proxyVsock,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.stopVsockProxy,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.ipLinkSet,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.ipAddrAdd,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.ipRouteAddLink,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.ipRouteAddDefault,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.configureDns,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.configureHosts,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.sync,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.kill,\n ]\n )\n\n public enum Methods {\n public static let mount = GRPCMethodDescriptor(\n name: \"Mount\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Mount\",\n type: GRPCCallType.unary\n )\n\n public static let umount = GRPCMethodDescriptor(\n name: \"Umount\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Umount\",\n type: GRPCCallType.unary\n )\n\n public static let setenv = GRPCMethodDescriptor(\n name: \"Setenv\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Setenv\",\n type: GRPCCallType.unary\n )\n\n public static let getenv = GRPCMethodDescriptor(\n name: \"Getenv\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Getenv\",\n type: GRPCCallType.unary\n )\n\n public static let mkdir = GRPCMethodDescriptor(\n name: \"Mkdir\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Mkdir\",\n type: GRPCCallType.unary\n )\n\n public static let sysctl = GRPCMethodDescriptor(\n name: \"Sysctl\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Sysctl\",\n type: GRPCCallType.unary\n )\n\n public static let setTime = GRPCMethodDescriptor(\n name: \"SetTime\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/SetTime\",\n type: GRPCCallType.unary\n )\n\n public static let setupEmulator = GRPCMethodDescriptor(\n name: \"SetupEmulator\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/SetupEmulator\",\n type: GRPCCallType.unary\n )\n\n public static let createProcess = GRPCMethodDescriptor(\n name: \"CreateProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/CreateProcess\",\n type: GRPCCallType.unary\n )\n\n public static let deleteProcess = GRPCMethodDescriptor(\n name: \"DeleteProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/DeleteProcess\",\n type: GRPCCallType.unary\n )\n\n public static let startProcess = GRPCMethodDescriptor(\n name: \"StartProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/StartProcess\",\n type: GRPCCallType.unary\n )\n\n public static let killProcess = GRPCMethodDescriptor(\n name: \"KillProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/KillProcess\",\n type: GRPCCallType.unary\n )\n\n public static let waitProcess = GRPCMethodDescriptor(\n name: \"WaitProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/WaitProcess\",\n type: GRPCCallType.unary\n )\n\n public static let resizeProcess = GRPCMethodDescriptor(\n name: \"ResizeProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ResizeProcess\",\n type: GRPCCallType.unary\n )\n\n public static let closeProcessStdin = GRPCMethodDescriptor(\n name: \"CloseProcessStdin\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/CloseProcessStdin\",\n type: GRPCCallType.unary\n )\n\n public static let proxyVsock = GRPCMethodDescriptor(\n name: \"ProxyVsock\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ProxyVsock\",\n type: GRPCCallType.unary\n )\n\n public static let stopVsockProxy = GRPCMethodDescriptor(\n name: \"StopVsockProxy\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/StopVsockProxy\",\n type: GRPCCallType.unary\n )\n\n public static let ipLinkSet = GRPCMethodDescriptor(\n name: \"IpLinkSet\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpLinkSet\",\n type: GRPCCallType.unary\n )\n\n public static let ipAddrAdd = GRPCMethodDescriptor(\n name: \"IpAddrAdd\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpAddrAdd\",\n type: GRPCCallType.unary\n )\n\n public static let ipRouteAddLink = GRPCMethodDescriptor(\n name: \"IpRouteAddLink\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpRouteAddLink\",\n type: GRPCCallType.unary\n )\n\n public static let ipRouteAddDefault = GRPCMethodDescriptor(\n name: \"IpRouteAddDefault\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpRouteAddDefault\",\n type: GRPCCallType.unary\n )\n\n public static let configureDns = GRPCMethodDescriptor(\n name: \"ConfigureDns\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ConfigureDns\",\n type: GRPCCallType.unary\n )\n\n public static let configureHosts = GRPCMethodDescriptor(\n name: \"ConfigureHosts\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ConfigureHosts\",\n type: GRPCCallType.unary\n )\n\n public static let sync = GRPCMethodDescriptor(\n name: \"Sync\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Sync\",\n type: GRPCCallType.unary\n )\n\n public static let kill = GRPCMethodDescriptor(\n name: \"Kill\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Kill\",\n type: GRPCCallType.unary\n )\n }\n}\n"], ["/containerization/Sources/Containerization/Agent/Vminitd+SocketRelay.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension Vminitd: SocketRelayAgent {\n /// Sets up a relay between a host socket to a newly created guest socket, or vice versa.\n public func relaySocket(port: UInt32, configuration: UnixSocketConfiguration) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest.with {\n $0.id = configuration.id\n $0.vsockPort = port\n\n if let perms = configuration.permissions {\n $0.guestSocketPermissions = UInt32(perms.rawValue)\n }\n\n switch configuration.direction {\n case .into:\n $0.guestPath = configuration.destination.path\n $0.action = .into\n case .outOf:\n $0.guestPath = configuration.source.path\n $0.action = .outOf\n }\n }\n _ = try await client.proxyVsock(request)\n }\n\n /// Stops the specified socket relay.\n public func stopSocketRelay(configuration: UnixSocketConfiguration) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest.with {\n $0.id = configuration.id\n }\n _ = try await client.stopVsockProxy(request)\n }\n}\n"], ["/containerization/Sources/Containerization/Image/ImageStore/ImageStore+OCILayout.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\nextension ImageStore {\n /// Exports the specified images and their associated layers to an OCI Image Layout directory.\n /// This function saves the images identified by the `references` array, including their\n /// manifests and layer blobs, into a directory structure compliant with the OCI Image Layout specification at the given `out` URL.\n ///\n /// - Parameters:\n /// - references: A list image references that exists in the `ImageStore` that are to be saved in the OCI Image Layout format.\n /// - out: A URL to a directory on disk at which the OCI Image Layout structure will be created.\n /// - platform: An optional parameter to indicate the platform to be saved for the images.\n /// Defaults to `nil` signifying that layers for all supported platforms by the images will be saved.\n ///\n public func save(references: [String], out: URL, platform: Platform? = nil) async throws {\n let matcher = createPlatformMatcher(for: platform)\n let fileManager = FileManager.default\n let tempDir = fileManager.uniqueTemporaryDirectory()\n defer {\n try? fileManager.removeItem(at: tempDir)\n }\n\n var toSave: [Image] = []\n for reference in references {\n let image = try await self.get(reference: reference)\n let allowedMediaTypes = [MediaTypes.dockerManifestList, MediaTypes.index]\n guard allowedMediaTypes.contains(image.mediaType) else {\n throw ContainerizationError(.internalError, message: \"Cannot save image \\(image.reference) with Index media type \\(image.mediaType)\")\n }\n toSave.append(image)\n }\n let client = try LocalOCILayoutClient(root: out)\n var saved: [Descriptor] = []\n\n for image in toSave {\n let ref = try Reference.parse(image.reference)\n let name = ref.path\n guard let tag = ref.tag ?? ref.digest else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid tag/digest for image reference \\(image.reference)\")\n }\n let operation = ExportOperation(name: name, tag: tag, contentStore: self.contentStore, client: client, progress: nil)\n var descriptor = try await operation.export(index: image.descriptor, platforms: matcher)\n client.setImageReferenceAnnotation(descriptor: &descriptor, reference: image.reference)\n saved.append(descriptor)\n }\n try client.createOCILayoutStructure(directory: out, manifests: saved)\n }\n\n /// Imports one or more images and their associated layers from an OCI Image Layout directory.\n ///\n /// - Parameters:\n /// - directory: A URL to a directory on disk at that follows the OCI Image Layout structure.\n /// - progress: An optional handler over which progress update events about the load operation can be received.\n /// - Returns: The list of images that were loaded into the `ImageStore`.\n ///\n public func load(from directory: URL, progress: ProgressHandler? = nil) async throws -> [Image] {\n let client = try LocalOCILayoutClient(root: directory)\n let index = try client.loadIndexFromOCILayout(directory: directory)\n let matcher = createPlatformMatcher(for: nil)\n\n var loaded: [Image.Description] = []\n let (id, tempDir) = try await self.contentStore.newIngestSession()\n do {\n for descriptor in index.manifests {\n guard let reference = client.getImageReferencefromDescriptor(descriptor: descriptor) else {\n continue\n }\n let ref = try Reference.parse(reference)\n let name = ref.path\n let operation = ImportOperation(name: name, contentStore: self.contentStore, client: client, ingestDir: tempDir, progress: progress)\n let indexDesc = try await operation.import(root: descriptor, matcher: matcher)\n loaded.append(Image.Description(reference: reference, descriptor: indexDesc))\n }\n\n let loadedImages = loaded\n let importedImages = try await self.lock.withLock { lock in\n var images: [Image] = []\n try await self.contentStore.completeIngestSession(id)\n for description in loadedImages {\n let img = try await self._create(description: description, lock: lock)\n images.append(img)\n }\n return images\n }\n guard importedImages.count > 0 else {\n throw ContainerizationError(.internalError, message: \"Failed to import image\")\n }\n return importedImages\n } catch {\n try? await self.contentStore.cancelIngestSession(id)\n throw error\n }\n }\n}\n"], ["/containerization/Sources/Containerization/Image/Unpacker/EXT4Unpacker.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\n#if os(macOS)\nimport ContainerizationArchive\nimport ContainerizationEXT4\nimport SystemPackage\n#endif\n\npublic struct EXT4Unpacker: Unpacker {\n let blockSizeInBytes: UInt64\n\n public init(blockSizeInBytes: UInt64) {\n self.blockSizeInBytes = blockSizeInBytes\n }\n\n public func unpack(_ image: Image, for platform: Platform, at path: URL, progress: ProgressHandler? = nil) async throws -> Mount {\n #if !os(macOS)\n throw ContainerizationError(.unsupported, message: \"Cannot unpack an image on current platform\")\n #else\n let blockPath = try prepareUnpackPath(path: path)\n let manifest = try await image.manifest(for: platform)\n let filesystem = try EXT4.Formatter(FilePath(path), minDiskSize: blockSizeInBytes)\n defer { try? filesystem.close() }\n\n for layer in manifest.layers {\n try Task.checkCancellation()\n let content = try await image.getContent(digest: layer.digest)\n\n let compression: ContainerizationArchive.Filter\n switch layer.mediaType {\n case MediaTypes.imageLayer, MediaTypes.dockerImageLayer:\n compression = .none\n case MediaTypes.imageLayerGzip, MediaTypes.dockerImageLayerGzip:\n compression = .gzip\n default:\n throw ContainerizationError(.unsupported, message: \"Media type \\(layer.mediaType) not supported.\")\n }\n try filesystem.unpack(\n source: content.path,\n format: .paxRestricted,\n compression: compression,\n progress: progress\n )\n }\n\n return .block(\n format: \"ext4\",\n source: blockPath,\n destination: \"/\",\n options: []\n )\n #endif\n }\n\n private func prepareUnpackPath(path: URL) throws -> String {\n let blockPath = path.absolutePath()\n guard !FileManager.default.fileExists(atPath: blockPath) else {\n throw ContainerizationError(.exists, message: \"block device already exists at \\(blockPath)\")\n }\n return blockPath\n }\n}\n"], ["/containerization/Sources/Integration/VMTests.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport Logging\n\nextension IntegrationSuite {\n func testMounts() async throws {\n let id = \"test-cat-mount\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n let directory = try createMountDirectory()\n config.process.arguments = [\"/bin/cat\", \"/mnt/hi.txt\"]\n config.mounts.append(.share(source: directory.path, destination: \"/mnt\"))\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n let value = String(data: buffer.data, encoding: .utf8)\n guard value == \"hello\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned from file 'hello' != '\\(String(data: buffer.data, encoding: .utf8)!)\")\n\n }\n }\n\n func testNestedVirtualizationEnabled() async throws {\n let id = \"test-nested-virt\"\n\n let bs = try await bootstrap()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/true\"]\n config.virtualization = true\n }\n\n do {\n try await container.create()\n try await container.start()\n } catch {\n if let err = error as? ContainerizationError {\n if err.code == .unsupported {\n throw SkipTest(reason: err.message)\n }\n }\n }\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n }\n\n func testContainerManagerCreate() async throws {\n let id = \"test-container-manager\"\n\n // Get the kernel from bootstrap\n let bs = try await bootstrap()\n\n // Create ContainerManager with kernel and initfs reference\n let manager = try ContainerManager(vmm: bs.vmm)\n defer {\n try? manager.delete(id)\n }\n\n let buffer = BufferWriter()\n let container = try await manager.create(\n id,\n image: bs.image,\n rootfs: bs.rootfs\n ) { config in\n config.process.arguments = [\"/bin/echo\", \"ContainerManager test\"]\n config.process.stdout = buffer\n }\n\n // Start the container\n try await container.create()\n try await container.start()\n\n // Wait for completion\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n let output = String(data: buffer.data, encoding: .utf8)\n guard output == \"ContainerManager test\\n\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned 'ContainerManager test' != '\\(output ?? \"nil\")'\")\n }\n }\n\n private func createMountDirectory() throws -> URL {\n let dir = FileManager.default.uniqueTemporaryDirectory(create: true)\n try \"hello\".write(to: dir.appendingPathComponent(\"hi.txt\"), atomically: true, encoding: .utf8)\n return dir\n }\n}\n"], ["/containerization/Sources/Containerization/Image/ImageStore/ImageStore+ReferenceManager.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\nextension ImageStore {\n /// A ReferenceManager handles the mappings between an image's\n /// reference and the underlying descriptor inside of a content store.\n internal actor ReferenceManager: Sendable {\n private let path: URL\n\n private typealias State = [String: Descriptor]\n private var images: State\n\n public init(path: URL) throws {\n try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true)\n\n self.path = path\n self.images = [:]\n }\n\n private func load() throws -> State {\n let statePath = self.path.appendingPathComponent(\"state.json\")\n guard FileManager.default.fileExists(atPath: statePath.absolutePath()) else {\n return [:]\n }\n do {\n let data = try Data(contentsOf: statePath)\n return try JSONDecoder().decode(State.self, from: data)\n } catch {\n throw ContainerizationError(.internalError, message: \"Failed to load image state \\(error.localizedDescription)\")\n }\n }\n\n private func save(_ state: State) throws {\n let statePath = self.path.appendingPathComponent(\"state.json\")\n try JSONEncoder().encode(state).write(to: statePath)\n }\n\n public func delete(reference: String) throws {\n var state = try self.load()\n state.removeValue(forKey: reference)\n try self.save(state)\n }\n\n public func delete(image: Image.Description) throws {\n try self.delete(reference: image.reference)\n }\n\n public func create(description: Image.Description) throws {\n var state = try self.load()\n state[description.reference] = description.descriptor\n try self.save(state)\n }\n\n public func list() throws -> [Image.Description] {\n let state = try self.load()\n return state.map { key, val in\n let description = Image.Description(reference: key, descriptor: val)\n return description\n }\n }\n\n public func get(reference: String) throws -> Image.Description {\n let images = try self.list()\n let hit = images.first(where: { image in\n image.reference == reference\n })\n guard let hit else {\n throw ContainerizationError(.notFound, message: \"image \\(reference) not found\")\n }\n return hit\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/RegistryClient+Token.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport ContainerizationError\nimport Foundation\n\nstruct TokenRequest {\n public static let authenticateHeaderName = \"WWW-Authenticate\"\n\n /// The credentials that will be used in the authentication header when fetching the token.\n let authentication: Authentication?\n /// The realm against which the token should be requested.\n let realm: String\n /// The name of the service which hosts the resource.\n let service: String\n /// Whether to return a refresh token along with the bearer token.\n let offlineToken: Bool\n /// String identifying the client.\n let clientId: String\n /// The resource in question, formatted as one of the space-delimited entries from the scope parameters from the WWW-Authenticate header shown above.\n let scope: String?\n\n init(\n realm: String,\n service: String,\n clientId: String,\n scope: String?,\n offlineToken: Bool = false,\n authentication: Authentication? = nil\n ) {\n self.realm = realm\n self.service = service\n self.offlineToken = offlineToken\n self.clientId = clientId\n self.scope = scope\n self.authentication = authentication\n }\n}\n\nstruct TokenResponse: Codable, Hashable {\n /// An opaque Bearer token that clients should supply to subsequent requests in the Authorization header.\n let token: String?\n /// For compatibility with OAuth 2.0, we will also accept token under the name access_token.\n /// At least one of these fields must be specified, but both may also appear (for compatibility with older clients).\n /// When both are specified, they should be equivalent; if they differ the client's choice is undefined.\n let accessToken: String?\n /// The duration in seconds since the token was issued that it will remain valid.\n /// When omitted, this defaults to 60 seconds.\n let expiresIn: UInt?\n /// The RFC3339-serialized UTC standard time at which a given token was issued.\n /// If issued_at is omitted, the expiration is from when the token exchange completed.\n let issuedAt: String?\n /// Token which can be used to get additional access tokens for the same subject with different scopes.\n /// This token should be kept secure by the client and only sent to the authorization server which issues bearer tokens.\n /// This field will only be set when `offline_token=true` is provided in the request.\n let refreshToken: String?\n\n var scope: String?\n\n private enum CodingKeys: String, CodingKey {\n case token = \"token\"\n case accessToken = \"access_token\"\n case expiresIn = \"expires_in\"\n case issuedAt = \"issued_at\"\n case refreshToken = \"refresh_token\"\n }\n\n func getToken() -> String? {\n if let t = token ?? accessToken {\n return \"Bearer \\(t)\"\n }\n return nil\n }\n\n func isValid(scope: String?) -> Bool {\n guard let issuedAt else {\n return false\n }\n let isoFormatter = ISO8601DateFormatter()\n isoFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]\n guard let issued = isoFormatter.date(from: issuedAt) else {\n return false\n }\n let expiresIn = expiresIn ?? 0\n let now = Date()\n let elapsed = now.timeIntervalSince(issued)\n guard elapsed < Double(expiresIn) else {\n return false\n }\n if let requiredScope = scope {\n return requiredScope == self.scope\n }\n return false\n }\n}\n\nstruct AuthenticateChallenge: Equatable {\n let type: String\n let realm: String?\n let service: String?\n let scope: String?\n let error: String?\n\n init(type: String, realm: String?, service: String?, scope: String?, error: String?) {\n self.type = type\n self.realm = realm\n self.service = service\n self.scope = scope\n self.error = error\n }\n\n init(type: String, values: [String: String]) {\n self.type = type\n self.realm = values[\"realm\"]\n self.service = values[\"service\"]\n self.scope = values[\"scope\"]\n self.error = values[\"error\"]\n }\n}\n\nextension RegistryClient {\n /// Fetch an auto token for all subsequent HTTP requests\n /// See https://docs.docker.com/registry/spec/auth/token/\n internal func fetchToken(request: TokenRequest) async throws -> TokenResponse {\n guard var components = URLComponents(string: request.realm) else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot create URL from \\(request.realm)\")\n }\n components.queryItems = [\n URLQueryItem(name: \"client_id\", value: request.clientId),\n URLQueryItem(name: \"service\", value: request.service),\n ]\n var scope = \"\"\n if let reqScope = request.scope {\n scope = reqScope\n components.queryItems?.append(URLQueryItem(name: \"scope\", value: reqScope))\n }\n\n if request.offlineToken {\n components.queryItems?.append(URLQueryItem(name: \"offline_token\", value: \"true\"))\n }\n var response: TokenResponse = try await requestJSON(components: components, headers: [])\n response.scope = scope\n return response\n }\n\n internal func createTokenRequest(parsing authenticateHeaders: [String]) throws -> TokenRequest {\n let parsedHeaders = Self.parseWWWAuthenticateHeaders(headers: authenticateHeaders)\n let bearerChallenge = parsedHeaders.first { $0.type == \"Bearer\" }\n guard let bearerChallenge else {\n throw ContainerizationError(.invalidArgument, message: \"Missing Bearer challenge in \\(TokenRequest.authenticateHeaderName) header\")\n }\n guard let realm = bearerChallenge.realm else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot parse realm from \\(TokenRequest.authenticateHeaderName) header\")\n }\n guard let service = bearerChallenge.service else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot parse service from \\(TokenRequest.authenticateHeaderName) header\")\n }\n let scope = bearerChallenge.scope\n let tokenRequest = TokenRequest(realm: realm, service: service, clientId: self.clientID, scope: scope, authentication: self.authentication)\n return tokenRequest\n }\n\n internal static func parseWWWAuthenticateHeaders(headers: [String]) -> [AuthenticateChallenge] {\n var parsed: [String: [String: String]] = [:]\n for challenge in headers {\n let trimmedChallenge = challenge.trimmingCharacters(in: .whitespacesAndNewlines)\n let parts = trimmedChallenge.split(separator: \" \", maxSplits: 1)\n guard parts.count == 2 else {\n continue\n }\n guard let scheme = parts.first else {\n continue\n }\n var params: [String: String] = [:]\n let header = String(parts[1])\n let pattern = #\"(\\w+)=\"([^\"]+)\"#\n let regex = try! NSRegularExpression(pattern: pattern, options: [])\n let matches = regex.matches(in: header, options: [], range: NSRange(header.startIndex..., in: header))\n for match in matches {\n if let keyRange = Range(match.range(at: 1), in: header),\n let valueRange = Range(match.range(at: 2), in: header)\n {\n let key = String(header[keyRange])\n let value = String(header[valueRange])\n params[key] = value\n }\n }\n parsed[String(scheme)] = params\n }\n var parsedChallenges: [AuthenticateChallenge] = []\n for (type, values) in parsed {\n parsedChallenges.append(.init(type: type, values: values))\n }\n return parsedChallenges\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+FileTree.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\nextension EXT4 {\n class FileTree {\n class FileTreeNode {\n let inode: InodeNumber\n let name: String\n var children: [Ptr] = []\n var blocks: (start: UInt32, end: UInt32)?\n var additionalBlocks: [(start: UInt32, end: UInt32)]?\n var link: InodeNumber?\n private var parent: Ptr?\n\n init(\n inode: InodeNumber,\n name: String,\n parent: Ptr?,\n children: [Ptr] = [],\n blocks: (start: UInt32, end: UInt32)? = nil,\n additionalBlocks: [(start: UInt32, end: UInt32)]? = nil,\n link: InodeNumber? = nil\n ) {\n self.inode = inode\n self.name = name\n self.children = children\n self.blocks = blocks\n self.additionalBlocks = additionalBlocks\n self.link = link\n self.parent = parent\n }\n\n deinit {\n self.children.removeAll()\n self.children = []\n self.blocks = nil\n self.additionalBlocks = nil\n self.link = nil\n }\n\n var path: FilePath? {\n var components: [String] = [self.name]\n var _ptr = self.parent\n while let ptr = _ptr {\n components.append(ptr.pointee.name)\n _ptr = ptr.pointee.parent\n }\n guard let last = components.last else {\n return nil\n }\n guard components.count > 1 else {\n return FilePath(last)\n }\n components = components.dropLast()\n let path = components.reversed().joined(separator: \"/\")\n guard let data = path.data(using: .utf8) else {\n return nil\n }\n guard let dataPath = String(data: data, encoding: .utf8) else {\n return nil\n }\n return FilePath(dataPath).pushing(FilePath(last)).lexicallyNormalized()\n }\n }\n\n var root: Ptr\n\n init(_ root: InodeNumber, _ name: String) {\n self.root = Ptr.allocate(capacity: 1)\n self.root.initialize(to: FileTreeNode(inode: root, name: name, parent: nil))\n }\n\n func lookup(path: FilePath) -> Ptr? {\n var components: [String] = path.items\n var node = self.root\n if components.first == \"/\" {\n components = Array(components.dropFirst())\n }\n if components.count == 0 {\n return node\n }\n for component in components {\n var found = false\n for childPtr in node.pointee.children {\n let child = childPtr.pointee\n if child.name == component {\n node = childPtr\n found = true\n break\n }\n }\n guard found else {\n return nil\n }\n }\n return node\n }\n }\n}\n"], ["/containerization/vminitd/Sources/vmexec/vmexec.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// NOTE: This binary implements a very small subset of the OCI runtime spec, mostly just\n/// the process configurations. Mounts are somewhat functional, but masked and read only paths\n/// aren't checked today. Today the namespaces are also ignored, and we always spawn a new pid\n/// and mount namespace.\n\nimport ArgumentParser\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport LCShim\nimport Logging\nimport Musl\n\n@main\nstruct App: ParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"vmexec\",\n version: \"0.1.0\",\n subcommands: [\n ExecCommand.self,\n RunCommand.self,\n ]\n )\n\n static let standardErrorLock = NSLock()\n\n @Sendable\n static func standardError(label: String) -> StreamLogHandler {\n standardErrorLock.withLock {\n StreamLogHandler.standardError(label: label)\n }\n }\n}\n\nextension App {\n /// Applies O_CLOEXEC to all file descriptors currently open for\n /// the process except the stdio fd values\n static func applyCloseExecOnFDs() throws {\n let minFD = 2 // stdin, stdout, stderr should be preserved\n\n let fdList = try FileManager.default.contentsOfDirectory(atPath: \"/proc/self/fd\")\n\n for fdStr in fdList {\n guard let fd = Int(fdStr) else {\n continue\n }\n if fd <= minFD {\n continue\n }\n\n _ = fcntl(Int32(fd), F_SETFD, FD_CLOEXEC)\n }\n }\n\n static func exec(process: ContainerizationOCI.Process) throws {\n let executable = strdup(process.args[0])\n var argv = process.args.map { strdup($0) }\n argv += [nil]\n\n let env = process.env.map { strdup($0) } + [nil]\n let cwd = process.cwd\n\n // switch cwd\n guard chdir(cwd) == 0 else {\n throw App.Errno(stage: \"chdir(cwd)\", info: \"Failed to change directory to '\\(cwd)'\")\n }\n\n guard execvpe(executable, argv, env) != -1 else {\n throw App.Errno(stage: \"execvpe(\\(String(describing: executable)))\", info: \"Failed to exec [\\(process.args.joined(separator: \" \"))]\")\n }\n fatalError(\"execvpe failed\")\n }\n\n static func setPermissions(user: ContainerizationOCI.User) throws {\n if user.additionalGids.count > 0 {\n guard setgroups(user.additionalGids.count, user.additionalGids) == 0 else {\n throw App.Errno(stage: \"setgroups()\")\n }\n }\n guard setgid(user.gid) == 0 else {\n throw App.Errno(stage: \"setgid()\")\n }\n // NOTE: setuid has to be done last because once the uid has been\n // changed, then the process will lose privilege to set the group\n // and supplementary groups\n guard setuid(user.uid) == 0 else {\n throw App.Errno(stage: \"setuid()\")\n }\n }\n\n static func fixStdioPerms(user: ContainerizationOCI.User) throws {\n for i in 0...2 {\n var fdStat = stat()\n try withUnsafeMutablePointer(to: &fdStat) { pointer in\n guard fstat(Int32(i), pointer) == 0 else {\n throw App.Errno(stage: \"fstat(fd)\")\n }\n }\n\n let desired = uid_t(user.uid)\n if fdStat.st_uid != desired {\n guard fchown(Int32(i), desired, fdStat.st_gid) != -1 else {\n throw App.Errno(stage: \"fchown(\\(i))\")\n }\n }\n }\n }\n\n static func setRLimits(rlimits: [ContainerizationOCI.POSIXRlimit]) throws {\n for rl in rlimits {\n var limit = rlimit(rlim_cur: rl.soft, rlim_max: rl.hard)\n let resource: Int32\n switch rl.type {\n case \"RLIMIT_AS\":\n resource = RLIMIT_AS\n case \"RLIMIT_CORE\":\n resource = RLIMIT_CORE\n case \"RLIMIT_CPU\":\n resource = RLIMIT_CPU\n case \"RLIMIT_DATA\":\n resource = RLIMIT_DATA\n case \"RLIMIT_FSIZE\":\n resource = RLIMIT_FSIZE\n case \"RLIMIT_NOFILE\":\n resource = RLIMIT_NOFILE\n case \"RLIMIT_STACK\":\n resource = RLIMIT_STACK\n case \"RLIMIT_NPROC\":\n resource = RLIMIT_NPROC\n case \"RLIMIT_RSS\":\n resource = RLIMIT_RSS\n case \"RLIMIT_MEMLOCK\":\n resource = RLIMIT_MEMLOCK\n default:\n errno = EINVAL\n throw App.Errno(stage: \"rlimit key unknown\")\n }\n guard setrlimit(resource, &limit) == 0 else {\n throw App.Errno(stage: \"setrlimit()\")\n }\n }\n }\n\n static func Errno(stage: String, info: String = \"\") -> ContainerizationError {\n let posix = POSIXError(.init(rawValue: errno)!, userInfo: [\"stage\": stage])\n return ContainerizationError(.internalError, message: \"\\(info) \\(String(describing: posix))\")\n }\n}\n"], ["/containerization/Sources/Containerization/Image/KernelImage.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\n/// A multi-arch kernel image represented by an OCI image.\npublic struct KernelImage: Sendable {\n /// The media type for a kernel image.\n public static let mediaType = \"application/vnd.apple.containerization.kernel\"\n\n /// The name or reference of the image.\n public var name: String { image.reference }\n\n let image: Image\n\n public init(image: Image) {\n self.image = image\n }\n}\n\nextension KernelImage {\n /// Return the kernel from a multi arch image for a specific system platform.\n public func kernel(for platform: SystemPlatform) async throws -> Kernel {\n let manifest = try await image.manifest(for: platform.ociPlatform())\n guard let descriptor = manifest.layers.first, descriptor.mediaType == Self.mediaType else {\n throw ContainerizationError(.notFound, message: \"kernel descriptor for \\(platform) not found\")\n }\n let content = try await image.getContent(digest: descriptor.digest)\n return Kernel(\n path: content.path,\n platform: platform\n )\n }\n\n /// Create a new kernel image with the reference as the name.\n /// This will create a multi arch image containing kernel's for each provided architecture.\n public static func create(reference: String, binaries: [Kernel], labels: [String: String] = [:], imageStore: ImageStore, contentStore: ContentStore) async throws -> KernelImage\n {\n let indexDescriptorStore = AsyncStore()\n try await contentStore.ingest { ingestPath in\n var descriptors = [Descriptor]()\n let writer = try ContentWriter(for: ingestPath)\n\n for kernel in binaries {\n var result = try writer.create(from: kernel.path)\n let platform = kernel.platform.ociPlatform()\n let layerDescriptor = Descriptor(\n mediaType: mediaType,\n digest: result.digest.digestString,\n size: result.size,\n platform: platform)\n let rootfsConfig = ContainerizationOCI.Rootfs(type: \"layers\", diffIDs: [result.digest.digestString])\n let runtimeConfig = ContainerizationOCI.ImageConfig(labels: labels)\n let imageConfig = ContainerizationOCI.Image(architecture: platform.architecture, os: platform.os, config: runtimeConfig, rootfs: rootfsConfig)\n\n result = try writer.create(from: imageConfig)\n let configDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.imageConfig, digest: result.digest.digestString, size: result.size)\n\n let manifest = Manifest(config: configDescriptor, layers: [layerDescriptor])\n result = try writer.create(from: manifest)\n let manifestDescriptor = Descriptor(\n mediaType: ContainerizationOCI.MediaTypes.imageManifest, digest: result.digest.digestString, size: result.size, platform: platform)\n descriptors.append(manifestDescriptor)\n }\n let index = ContainerizationOCI.Index(manifests: descriptors)\n let result = try writer.create(from: index)\n let indexDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.index, digest: result.digest.digestString, size: result.size)\n await indexDescriptorStore.set(indexDescriptor)\n }\n\n guard let indexDescriptor = await indexDescriptorStore.get() else {\n throw ContainerizationError(.notFound, message: \"image for \\(reference) not found\")\n }\n\n let description = Image.Description(reference: reference, descriptor: indexDescriptor)\n let image = try await imageStore.create(description: description)\n return KernelImage(image: image)\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/LocalContent.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Crypto\nimport Foundation\n\npublic final class LocalContent: Content {\n public let path: URL\n private let file: FileHandle\n\n public init(path: URL) throws {\n guard FileManager.default.fileExists(atPath: path.path) else {\n throw ContainerizationError(.notFound, message: \"Content at path \\(path.absolutePath())\")\n }\n\n self.file = try FileHandle(forReadingFrom: path)\n self.path = path\n }\n\n public func digest() throws -> SHA256.Digest {\n let bufferSize = 64 * 1024 // 64 KB\n var hasher = SHA256()\n\n try self.file.seek(toOffset: 0)\n while case let data = file.readData(ofLength: bufferSize), !data.isEmpty {\n hasher.update(data: data)\n }\n\n let digest = hasher.finalize()\n\n try self.file.seek(toOffset: 0)\n return digest\n }\n\n public func data(offset: UInt64 = 0, length size: Int = 0) throws -> Data? {\n try file.seek(toOffset: offset)\n if size == 0 {\n return try file.readToEnd()\n }\n return try file.read(upToCount: size)\n }\n\n public func data() throws -> Data {\n try Data(contentsOf: self.path)\n }\n\n public func size() throws -> UInt64 {\n let fileAttrs = try FileManager.default.attributesOfItem(atPath: self.path.absolutePath())\n if let size = fileAttrs[FileAttributeKey.size] as? UInt64 {\n return size\n }\n throw ContainerizationError(.internalError, message: \"Could not determine file size for \\(path.absolutePath())\")\n }\n\n public func decode() throws -> T where T: Decodable {\n let json = JSONDecoder()\n let data = try Data(contentsOf: self.path)\n return try json.decode(T.self, from: data)\n }\n\n deinit {\n try? self.file.close()\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/WriteEntry.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CArchive\nimport Foundation\n\n/// Represents a single entry (e.g., a file, directory, symbolic link)\n/// that is to be read/written into an archive.\npublic final class WriteEntry {\n let underlying: OpaquePointer\n\n public init(_ archive: ArchiveWriter) {\n underlying = archive_entry_new2(archive.underlying)\n }\n\n public init() {\n underlying = archive_entry_new()\n }\n\n deinit {\n archive_entry_free(underlying)\n }\n}\n\nextension WriteEntry {\n /// The size of the entry in bytes.\n public var size: Int64? {\n get {\n guard archive_entry_size_is_set(underlying) != 0 else { return nil }\n return archive_entry_size(underlying)\n }\n set {\n if let s = newValue {\n archive_entry_set_size(underlying, s)\n } else {\n archive_entry_unset_size(underlying)\n }\n }\n }\n\n /// The mode of the entry.\n public var permissions: mode_t {\n get {\n archive_entry_perm(underlying)\n }\n set {\n archive_entry_set_perm(underlying, newValue)\n }\n }\n\n /// The owner id of the entry.\n public var owner: uid_t? {\n get {\n uid_t(exactly: archive_entry_uid(underlying))\n }\n set {\n archive_entry_set_uid(underlying, Int64(newValue ?? 0))\n }\n }\n\n /// The group id of the entry\n public var group: gid_t? {\n get {\n gid_t(exactly: archive_entry_gid(underlying))\n }\n set {\n archive_entry_set_gid(underlying, Int64(newValue ?? 0))\n }\n }\n\n /// The path of file this entry hardlinks to\n public var hardlink: String? {\n get {\n guard let cstr = archive_entry_hardlink(underlying) else {\n return nil\n }\n return String(cString: cstr)\n }\n set {\n guard let newValue else {\n archive_entry_set_hardlink(underlying, nil)\n return\n }\n newValue.withCString {\n archive_entry_set_hardlink(underlying, $0)\n }\n }\n }\n\n /// The UTF-8 encoded path of file this entry hardlinks to\n public var hardlinkUtf8: String? {\n get {\n guard let cstr = archive_entry_hardlink_utf8(underlying) else {\n return nil\n }\n return String(cString: cstr, encoding: .utf8)\n }\n set {\n guard let newValue else {\n archive_entry_set_hardlink_utf8(underlying, nil)\n return\n }\n newValue.withCString {\n archive_entry_set_hardlink_utf8(underlying, $0)\n }\n }\n }\n\n /// The string representation of the permissions of the entry\n public var strmode: String? {\n if let cstr = archive_entry_strmode(underlying) {\n return String(cString: cstr)\n }\n return nil\n }\n\n /// The type of file this entry represents.\n public var fileType: URLFileResourceType {\n get {\n switch archive_entry_filetype(underlying) {\n case S_IFIFO: return .namedPipe\n case S_IFCHR: return .characterSpecial\n case S_IFDIR: return .directory\n case S_IFBLK: return .blockSpecial\n case S_IFREG: return .regular\n case S_IFLNK: return .symbolicLink\n case S_IFSOCK: return .socket\n default: return .unknown\n }\n }\n set {\n switch newValue {\n case .namedPipe: archive_entry_set_filetype(underlying, UInt32(S_IFIFO as mode_t))\n case .characterSpecial: archive_entry_set_filetype(underlying, UInt32(S_IFCHR as mode_t))\n case .directory: archive_entry_set_filetype(underlying, UInt32(S_IFDIR as mode_t))\n case .blockSpecial: archive_entry_set_filetype(underlying, UInt32(S_IFBLK as mode_t))\n case .regular: archive_entry_set_filetype(underlying, UInt32(S_IFREG as mode_t))\n case .symbolicLink: archive_entry_set_filetype(underlying, UInt32(S_IFLNK as mode_t))\n case .socket: archive_entry_set_filetype(underlying, UInt32(S_IFSOCK as mode_t))\n default: archive_entry_set_filetype(underlying, 0)\n }\n }\n }\n\n /// The date that the entry was last accessed\n public var contentAccessDate: Date? {\n get {\n Date(\n underlying,\n archive_entry_atime_is_set,\n archive_entry_atime,\n archive_entry_atime_nsec)\n }\n set {\n setDate(\n newValue,\n underlying, archive_entry_set_atime,\n archive_entry_unset_atime)\n }\n }\n\n /// The date that the entry was created\n public var creationDate: Date? {\n get {\n Date(\n underlying,\n archive_entry_ctime_is_set,\n archive_entry_ctime,\n archive_entry_ctime_nsec)\n }\n set {\n setDate(\n newValue,\n underlying, archive_entry_set_ctime,\n archive_entry_unset_ctime)\n }\n }\n\n /// The date that the entry was modified\n public var modificationDate: Date? {\n get {\n Date(\n underlying,\n archive_entry_mtime_is_set,\n archive_entry_mtime,\n archive_entry_mtime_nsec)\n }\n set {\n setDate(\n newValue,\n underlying, archive_entry_set_mtime,\n archive_entry_unset_mtime)\n }\n }\n\n /// The file path of the entry\n public var path: String? {\n get {\n guard let pathname = archive_entry_pathname(underlying) else {\n return nil\n }\n return String(cString: pathname)\n }\n set {\n guard let newValue else {\n archive_entry_set_pathname(underlying, nil)\n return\n }\n newValue.withCString {\n archive_entry_set_pathname(underlying, $0)\n }\n }\n }\n\n /// The UTF-8 encoded file path of the entry\n public var pathUtf8: String? {\n get {\n guard let pathname = archive_entry_pathname_utf8(underlying) else {\n return nil\n }\n return String(cString: pathname)\n }\n set {\n guard let newValue else {\n archive_entry_set_pathname_utf8(underlying, nil)\n return\n }\n newValue.withCString {\n archive_entry_set_pathname_utf8(underlying, $0)\n }\n }\n }\n\n /// The symlink target that the entry points to\n public var symlinkTarget: String? {\n get {\n guard let target = archive_entry_symlink(underlying) else {\n return nil\n }\n return String(cString: target)\n }\n set {\n guard let newValue else {\n archive_entry_set_symlink(underlying, nil)\n return\n }\n newValue.withCString {\n archive_entry_set_symlink(underlying, $0)\n }\n }\n }\n\n /// The extended attributes of the entry\n public var xattrs: [String: Data] {\n get {\n archive_entry_xattr_reset(self.underlying)\n var attrs: [String: Data] = [:]\n var namePtr: UnsafePointer?\n var valuePtr: UnsafeRawPointer?\n var size: Int = 0\n while archive_entry_xattr_next(self.underlying, &namePtr, &valuePtr, &size) == 0 {\n let _name = namePtr.map { String(cString: $0) }\n let _value = valuePtr.map { Data(bytes: $0, count: size) }\n guard let name = _name, let value = _value else {\n continue\n }\n attrs[name] = value\n }\n return attrs\n }\n set {\n archive_entry_xattr_clear(self.underlying)\n for (key, value) in newValue {\n value.withUnsafeBytes { ptr in\n archive_entry_xattr_add_entry(self.underlying, key, ptr.baseAddress, [UInt8](value).count)\n }\n }\n }\n }\n\n fileprivate func setDate(\n _ date: Date?, _ underlying: OpaquePointer, _ setter: (OpaquePointer, time_t, CLong) -> Void,\n _ unset: (OpaquePointer) -> Void\n ) {\n if let d = date {\n let ti = d.timeIntervalSince1970\n let seconds = floor(ti)\n let nsec = max(0, min(1_000_000_000, ti - seconds * 1_000_000_000))\n setter(underlying, time_t(seconds), CLong(nsec))\n } else {\n unset(underlying)\n }\n }\n}\n\nextension Date {\n init?(\n _ underlying: OpaquePointer, _ isSet: (OpaquePointer) -> CInt, _ seconds: (OpaquePointer) -> time_t,\n _ nsec: (OpaquePointer) -> CLong\n ) {\n guard isSet(underlying) != 0 else { return nil }\n let ti = TimeInterval(seconds(underlying)) + TimeInterval(nsec(underlying)) * 0.000_000_001\n self.init(timeIntervalSince1970: ti)\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Spec.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// NOTE: This is not a complete recreation of the runtime spec. Other platforms outside of Linux\n/// have been left off, and some APIs for Linux aren't present. This was manually ported starting\n/// at the v1.2.0 release.\n\npublic struct Spec: Codable, Sendable {\n public var version: String\n public var hooks: Hook?\n public var process: Process?\n public var hostname, domainname: String\n public var mounts: [Mount]\n public var annotations: [String: String]?\n public var root: Root?\n public var linux: Linux?\n\n public init(\n version: String = \"\",\n hooks: Hook? = nil,\n process: Process? = nil,\n hostname: String = \"\",\n domainname: String = \"\",\n mounts: [Mount] = [],\n annotations: [String: String]? = nil,\n root: Root? = nil,\n linux: Linux? = nil\n ) {\n self.version = version\n self.hooks = hooks\n self.process = process\n self.hostname = hostname\n self.domainname = domainname\n self.mounts = mounts\n self.annotations = annotations\n self.root = root\n self.linux = linux\n }\n\n public enum CodingKeys: String, CodingKey {\n case version = \"ociVersion\"\n case hooks\n case process\n case hostname\n case domainname\n case mounts\n case annotations\n case root\n case linux\n }\n}\n\npublic struct Process: Codable, Sendable {\n public var cwd: String\n public var env: [String]\n public var consoleSize: Box?\n public var selinuxLabel: String\n public var noNewPrivileges: Bool\n public var commandLine: String\n public var oomScoreAdj: Int?\n public var capabilities: LinuxCapabilities?\n public var apparmorProfile: String\n public var user: User\n public var rlimits: [POSIXRlimit]\n public var args: [String]\n public var terminal: Bool\n\n public init(\n args: [String] = [],\n cwd: String = \"/\",\n env: [String] = [],\n consoleSize: Box? = nil,\n selinuxLabel: String = \"\",\n noNewPrivileges: Bool = false,\n commandLine: String = \"\",\n oomScoreAdj: Int? = nil,\n capabilities: LinuxCapabilities? = nil,\n apparmorProfile: String = \"\",\n user: User = .init(),\n rlimits: [POSIXRlimit] = [],\n terminal: Bool = false\n ) {\n self.cwd = cwd\n self.env = env\n self.consoleSize = consoleSize\n self.selinuxLabel = selinuxLabel\n self.noNewPrivileges = noNewPrivileges\n self.commandLine = commandLine\n self.oomScoreAdj = oomScoreAdj\n self.capabilities = capabilities\n self.apparmorProfile = apparmorProfile\n self.user = user\n self.rlimits = rlimits\n self.args = args\n self.terminal = terminal\n }\n\n public init(from config: ImageConfig) {\n let cwd = config.workingDir ?? \"/\"\n let env = config.env ?? []\n let args = (config.entrypoint ?? []) + (config.cmd ?? [])\n let user: User = {\n if let rawString = config.user {\n return User(username: rawString)\n }\n return User()\n }()\n self.init(args: args, cwd: cwd, env: env, user: user)\n }\n}\n\npublic struct LinuxCapabilities: Codable, Sendable {\n public var bounding: [String]\n public var effective: [String]\n public var inheritable: [String]\n public var permitted: [String]\n public var ambient: [String]\n\n public init(\n bounding: [String],\n effective: [String],\n inheritable: [String],\n permitted: [String],\n ambient: [String]\n ) {\n self.bounding = bounding\n self.effective = effective\n self.inheritable = inheritable\n self.permitted = permitted\n self.ambient = ambient\n }\n}\n\npublic struct Box: Codable, Sendable {\n var height, width: UInt\n\n public init(height: UInt, width: UInt) {\n self.height = height\n self.width = width\n }\n}\n\npublic struct User: Codable, Sendable {\n public var uid: UInt32\n public var gid: UInt32\n public var umask: UInt32?\n public var additionalGids: [UInt32]\n public var username: String\n\n public init(\n uid: UInt32 = 0,\n gid: UInt32 = 0,\n umask: UInt32? = nil,\n additionalGids: [UInt32] = [],\n username: String = \"\"\n ) {\n self.uid = uid\n self.gid = gid\n self.umask = umask\n self.additionalGids = additionalGids\n self.username = username\n }\n}\n\npublic struct Root: Codable, Sendable {\n public var path: String\n public var readonly: Bool\n\n public init(path: String, readonly: Bool) {\n self.path = path\n self.readonly = readonly\n }\n}\n\npublic struct Mount: Codable, Sendable {\n public var type: String\n public var source: String\n public var destination: String\n public var options: [String]\n\n public var uidMappings: [LinuxIDMapping]\n public var gidMappings: [LinuxIDMapping]\n\n public init(\n type: String,\n source: String,\n destination: String,\n options: [String] = [],\n uidMappings: [LinuxIDMapping] = [],\n gidMappings: [LinuxIDMapping] = []\n ) {\n self.destination = destination\n self.type = type\n self.source = source\n self.options = options\n self.uidMappings = uidMappings\n self.gidMappings = gidMappings\n }\n}\n\npublic struct Hook: Codable, Sendable {\n public var path: String\n public var args: [String]\n public var env: [String]\n public var timeout: Int?\n\n public init(path: String, args: [String], env: [String], timeout: Int?) {\n self.path = path\n self.args = args\n self.env = env\n self.timeout = timeout\n }\n}\n\npublic struct Hooks: Codable, Sendable {\n public var prestart: [Hook]\n public var createRuntime: [Hook]\n public var createContainer: [Hook]\n public var startContainer: [Hook]\n public var poststart: [Hook]\n public var poststop: [Hook]\n\n public init(\n prestart: [Hook],\n createRuntime: [Hook],\n createContainer: [Hook],\n startContainer: [Hook],\n poststart: [Hook],\n poststop: [Hook]\n ) {\n self.prestart = prestart\n self.createRuntime = createRuntime\n self.createContainer = createContainer\n self.startContainer = startContainer\n self.poststart = poststart\n self.poststop = poststop\n }\n}\n\npublic struct Linux: Codable, Sendable {\n public var uidMappings: [LinuxIDMapping]\n public var gidMappings: [LinuxIDMapping]\n public var sysctl: [String: String]?\n public var resources: LinuxResources?\n public var cgroupsPath: String\n public var namespaces: [LinuxNamespace]\n public var devices: [LinuxDevice]\n public var seccomp: LinuxSeccomp?\n public var rootfsPropagation: String\n public var maskedPaths: [String]\n public var readonlyPaths: [String]\n public var mountLabel: String\n public var personality: LinuxPersonality?\n\n public init(\n uidMappings: [LinuxIDMapping] = [],\n gidMappings: [LinuxIDMapping] = [],\n sysctl: [String: String]? = nil,\n resources: LinuxResources? = nil,\n cgroupsPath: String = \"\",\n namespaces: [LinuxNamespace] = [],\n devices: [LinuxDevice] = [],\n seccomp: LinuxSeccomp? = nil,\n rootfsPropagation: String = \"\",\n maskedPaths: [String] = [],\n readonlyPaths: [String] = [],\n mountLabel: String = \"\",\n personality: LinuxPersonality? = nil\n ) {\n self.uidMappings = uidMappings\n self.gidMappings = gidMappings\n self.sysctl = sysctl\n self.resources = resources\n self.cgroupsPath = cgroupsPath\n self.namespaces = namespaces\n self.devices = devices\n self.seccomp = seccomp\n self.rootfsPropagation = rootfsPropagation\n self.maskedPaths = maskedPaths\n self.readonlyPaths = readonlyPaths\n self.mountLabel = mountLabel\n self.personality = personality\n }\n}\n\npublic struct LinuxNamespace: Codable, Sendable {\n public var type: LinuxNamespaceType\n public var path: String\n\n public init(type: LinuxNamespaceType, path: String = \"\") {\n self.type = type\n self.path = path\n }\n}\n\npublic enum LinuxNamespaceType: String, Codable, Sendable {\n case pid\n case network\n case uts\n case mount\n case ipc\n case user\n case cgroup\n}\n\npublic struct LinuxIDMapping: Codable, Sendable {\n public var containerID: UInt32\n public var hostID: UInt32\n public var size: UInt32\n\n public init(containerID: UInt32, hostID: UInt32, size: UInt32) {\n self.containerID = containerID\n self.hostID = hostID\n self.size = size\n }\n}\n\npublic struct POSIXRlimit: Codable, Sendable {\n public var type: String\n public var hard: UInt64\n public var soft: UInt64\n\n public init(type: String, hard: UInt64, soft: UInt64) {\n self.type = type\n self.hard = hard\n self.soft = soft\n }\n}\n\npublic struct LinuxHugepageLimit: Codable, Sendable {\n public var pagesize: String\n public var limit: UInt64\n\n public init(pagesize: String, limit: UInt64) {\n self.pagesize = pagesize\n self.limit = limit\n }\n}\n\npublic struct LinuxInterfacePriority: Codable, Sendable {\n public var name: String\n public var priority: UInt32\n\n public init(name: String, priority: UInt32) {\n self.name = name\n self.priority = priority\n }\n}\n\npublic struct LinuxBlockIODevice: Codable, Sendable {\n public var major: Int64\n public var minor: Int64\n\n public init(major: Int64, minor: Int64) {\n self.major = major\n self.minor = minor\n }\n}\n\npublic struct LinuxWeightDevice: Codable, Sendable {\n public var major: Int64\n public var minor: Int64\n public var weight: UInt16?\n public var leafWeight: UInt16?\n\n public init(major: Int64, minor: Int64, weight: UInt16?, leafWeight: UInt16?) {\n self.major = major\n self.minor = minor\n self.weight = weight\n self.leafWeight = leafWeight\n }\n}\n\npublic struct LinuxThrottleDevice: Codable, Sendable {\n public var major: Int64\n public var minor: Int64\n public var rate: UInt64\n\n public init(major: Int64, minor: Int64, rate: UInt64) {\n self.major = major\n self.minor = minor\n self.rate = rate\n }\n}\n\npublic struct LinuxBlockIO: Codable, Sendable {\n public var weight: UInt16?\n public var leafWeight: UInt16?\n public var weightDevice: [LinuxWeightDevice]\n public var throttleReadBpsDevice: [LinuxThrottleDevice]\n public var throttleWriteBpsDevice: [LinuxThrottleDevice]\n public var throttleReadIOPSDevice: [LinuxThrottleDevice]\n public var throttleWriteIOPSDevice: [LinuxThrottleDevice]\n\n public init(\n weight: UInt16?,\n leafWeight: UInt16?,\n weightDevice: [LinuxWeightDevice],\n throttleReadBpsDevice: [LinuxThrottleDevice],\n throttleWriteBpsDevice: [LinuxThrottleDevice],\n throttleReadIOPSDevice: [LinuxThrottleDevice],\n throttleWriteIOPSDevice: [LinuxThrottleDevice]\n ) {\n self.weight = weight\n self.leafWeight = leafWeight\n self.weightDevice = weightDevice\n self.throttleReadBpsDevice = throttleReadBpsDevice\n self.throttleWriteBpsDevice = throttleWriteBpsDevice\n self.throttleReadIOPSDevice = throttleReadIOPSDevice\n self.throttleWriteIOPSDevice = throttleWriteIOPSDevice\n }\n}\n\npublic struct LinuxMemory: Codable, Sendable {\n public var limit: Int64?\n public var reservation: Int64?\n public var swap: Int64?\n public var kernel: Int64?\n public var kernelTCP: Int64?\n public var swappiness: UInt64?\n public var disableOOMKiller: Bool?\n public var useHierarchy: Bool?\n public var checkBeforeUpdate: Bool?\n\n public init(\n limit: Int64? = nil,\n reservation: Int64? = nil,\n swap: Int64? = nil,\n kernel: Int64? = nil,\n kernelTCP: Int64? = nil,\n swappiness: UInt64? = nil,\n disableOOMKiller: Bool? = nil,\n useHierarchy: Bool? = nil,\n checkBeforeUpdate: Bool? = nil\n ) {\n self.limit = limit\n self.reservation = reservation\n self.swap = swap\n self.kernel = kernel\n self.kernelTCP = kernelTCP\n self.swappiness = swappiness\n self.disableOOMKiller = disableOOMKiller\n self.useHierarchy = useHierarchy\n self.checkBeforeUpdate = checkBeforeUpdate\n }\n}\n\npublic struct LinuxCPU: Codable, Sendable {\n public var shares: UInt64?\n public var quota: Int64?\n public var burst: UInt64?\n public var period: UInt64?\n public var realtimeRuntime: Int64?\n public var realtimePeriod: Int64?\n public var cpus: String\n public var mems: String\n public var idle: Int64?\n\n public init(\n shares: UInt64?,\n quota: Int64?,\n burst: UInt64?,\n period: UInt64?,\n realtimeRuntime: Int64?,\n realtimePeriod: Int64?,\n cpus: String,\n mems: String,\n idle: Int64?\n ) {\n self.shares = shares\n self.quota = quota\n self.burst = burst\n self.period = period\n self.realtimeRuntime = realtimeRuntime\n self.realtimePeriod = realtimePeriod\n self.cpus = cpus\n self.mems = mems\n self.idle = idle\n }\n}\n\npublic struct LinuxPids: Codable, Sendable {\n public var limit: Int64\n\n public init(limit: Int64) {\n self.limit = limit\n }\n}\n\npublic struct LinuxNetwork: Codable, Sendable {\n public var classID: UInt32?\n public var priorities: [LinuxInterfacePriority]\n\n public init(classID: UInt32?, priorities: [LinuxInterfacePriority]) {\n self.classID = classID\n self.priorities = priorities\n }\n}\n\npublic struct LinuxRdma: Codable, Sendable {\n public var hcsHandles: UInt32?\n public var hcaObjects: UInt32?\n\n public init(hcsHandles: UInt32?, hcaObjects: UInt32?) {\n self.hcsHandles = hcsHandles\n self.hcaObjects = hcaObjects\n }\n}\n\npublic struct LinuxResources: Codable, Sendable {\n public var devices: [LinuxDeviceCgroup]\n public var memory: LinuxMemory?\n public var cpu: LinuxCPU?\n public var pids: LinuxPids?\n public var blockIO: LinuxBlockIO?\n public var hugepageLimits: [LinuxHugepageLimit]\n public var network: LinuxNetwork?\n public var rdma: [String: LinuxRdma]?\n public var unified: [String: String]?\n\n public init(\n devices: [LinuxDeviceCgroup] = [],\n memory: LinuxMemory? = nil,\n cpu: LinuxCPU? = nil,\n pids: LinuxPids? = nil,\n blockIO: LinuxBlockIO? = nil,\n hugepageLimits: [LinuxHugepageLimit] = [],\n network: LinuxNetwork? = nil,\n rdma: [String: LinuxRdma]? = nil,\n unified: [String: String] = [:]\n ) {\n self.devices = devices\n self.memory = memory\n self.cpu = cpu\n self.pids = pids\n self.blockIO = blockIO\n self.hugepageLimits = hugepageLimits\n self.network = network\n self.rdma = rdma\n self.unified = unified\n }\n}\n\npublic struct LinuxDevice: Codable, Sendable {\n public var path: String\n public var type: String\n public var major: Int64\n public var minor: Int64\n public var fileMode: UInt32?\n public var uid: UInt32?\n public var gid: UInt32?\n\n public init(\n path: String,\n type: String,\n major: Int64,\n minor: Int64,\n fileMode: UInt32?,\n uid: UInt32?,\n gid: UInt32?\n ) {\n self.path = path\n self.type = type\n self.major = major\n self.minor = minor\n self.fileMode = fileMode\n self.uid = uid\n self.gid = gid\n }\n}\n\npublic struct LinuxDeviceCgroup: Codable, Sendable {\n public var allow: Bool\n public var type: String\n public var major: Int64?\n public var minor: Int64?\n public var access: String?\n\n public init(allow: Bool, type: String, major: Int64?, minor: Int64?, access: String?) {\n self.allow = allow\n self.type = type\n self.major = major\n self.minor = minor\n self.access = access\n }\n}\n\npublic enum LinuxPersonalityDomain: String, Codable, Sendable {\n case perLinux = \"LINUX\"\n case perLinux32 = \"LINUX32\"\n}\n\npublic struct LinuxPersonality: Codable, Sendable {\n public var domain: LinuxPersonalityDomain\n public var flags: [String]\n\n public init(domain: LinuxPersonalityDomain, flags: [String]) {\n self.domain = domain\n self.flags = flags\n }\n}\n\npublic struct LinuxSeccomp: Codable, Sendable {\n public var defaultAction: LinuxSeccompAction\n public var defaultErrnoRet: UInt?\n public var architectures: [Arch]\n public var flags: [LinuxSeccompFlag]\n public var listenerPath: String\n public var listenerMetadata: String\n public var syscalls: [LinuxSyscall]\n\n public init(\n defaultAction: LinuxSeccompAction,\n defaultErrnoRet: UInt?,\n architectures: [Arch],\n flags: [LinuxSeccompFlag],\n listenerPath: String,\n listenerMetadata: String,\n syscalls: [LinuxSyscall]\n ) {\n self.defaultAction = defaultAction\n self.defaultErrnoRet = defaultErrnoRet\n self.architectures = architectures\n self.flags = flags\n self.listenerPath = listenerPath\n self.listenerMetadata = listenerMetadata\n self.syscalls = syscalls\n }\n}\n\npublic enum LinuxSeccompFlag: String, Codable, Sendable {\n case flagLog = \"SECCOMP_FILTER_FLAG_LOG\"\n case flagSpecAllow = \"SECCOMP_FILTER_FLAG_SPEC_ALLOW\"\n case flagWaitKillableRecv = \"SECCOMP_FILTER_FLAG_WAIT_KILLABLE_RECV\"\n}\n\npublic enum Arch: String, Codable, Sendable {\n case archX86 = \"SCMP_ARCH_X86\"\n case archX86_64 = \"SCMP_ARCH_X86_64\"\n case archX32 = \"SCMP_ARCH_X32\"\n case archARM = \"SCMP_ARCH_ARM\"\n case archAARCH64 = \"SCMP_ARCH_AARCH64\"\n case archMIPS = \"SCMP_ARCH_MIPS\"\n case archMIPS64 = \"SCMP_ARCH_MIPS64\"\n case archMIPS64N32 = \"SCMP_ARCH_MIPS64N32\"\n case archMIPSEL = \"SCMP_ARCH_MIPSEL\"\n case archMIPSEL64 = \"SCMP_ARCH_MIPSEL64\"\n case archMIPSEL64N32 = \"SCMP_ARCH_MIPSEL64N32\"\n case archPPC = \"SCMP_ARCH_PPC\"\n case archPPC64 = \"SCMP_ARCH_PPC64\"\n case archPPC64LE = \"SCMP_ARCH_PPC64LE\"\n case archS390 = \"SCMP_ARCH_S390\"\n case archS390X = \"SCMP_ARCH_S390X\"\n case archPARISC = \"SCMP_ARCH_PARISC\"\n case archPARISC64 = \"SCMP_ARCH_PARISC64\"\n case archRISCV64 = \"SCMP_ARCH_RISCV64\"\n}\n\npublic enum LinuxSeccompAction: String, Codable, Sendable {\n case actKill = \"SCMP_ACT_KILL\"\n case actKillProcess = \"SCMP_ACT_KILL_PROCESS\"\n case actKillThread = \"SCMP_ACT_KILL_THREAD\"\n case actTrap = \"SCMP_ACT_TRAP\"\n case actErrno = \"SCMP_ACT_ERRNO\"\n case actTrace = \"SCMP_ACT_TRACE\"\n case actAllow = \"SCMP_ACT_ALLOW\"\n case actLog = \"SCMP_ACT_LOG\"\n case actNotify = \"SCMP_ACT_NOTIFY\"\n}\n\npublic enum LinuxSeccompOperator: String, Codable, Sendable {\n case opNotEqual = \"SCMP_CMP_NE\"\n case opLessThan = \"SCMP_CMP_LT\"\n case opLessEqual = \"SCMP_CMP_LE\"\n case opEqualTo = \"SCMP_CMP_EQ\"\n case opGreaterEqual = \"SCMP_CMP_GE\"\n case opGreaterThan = \"SCMP_CMP_GT\"\n case opMaskedEqual = \"SCMP_CMP_MASKED_EQ\"\n}\n\npublic struct LinuxSeccompArg: Codable, Sendable {\n public var index: UInt\n public var value: UInt64\n public var valueTwo: UInt64\n public var op: LinuxSeccompOperator\n\n public init(index: UInt, value: UInt64, valueTwo: UInt64, op: LinuxSeccompOperator) {\n self.index = index\n self.value = value\n self.valueTwo = valueTwo\n self.op = op\n }\n}\n\npublic struct LinuxSyscall: Codable, Sendable {\n public var names: [String]\n public var action: LinuxSeccompAction\n public var errnoRet: UInt?\n public var args: [LinuxSeccompArg]\n\n public init(\n names: [String],\n action: LinuxSeccompAction,\n errnoRet: UInt?,\n args: [LinuxSeccompArg]\n ) {\n self.names = names\n self.action = action\n self.errnoRet = errnoRet\n self.args = args\n }\n}\n"], ["/containerization/Sources/Containerization/SandboxContext/SandboxContext.pb.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// DO NOT EDIT.\n// swift-format-ignore-file\n// swiftlint:disable all\n//\n// Generated by the Swift generator plugin for the protocol buffer compiler.\n// Source: SandboxContext.proto\n//\n// For information on using the generated types, please see the documentation:\n// https://github.com/apple/swift-protobuf/\n\nimport Foundation\nimport SwiftProtobuf\n\n// If the compiler emits an error on this type, it is because this file\n// was generated by a version of the `protoc` Swift plug-in that is\n// incompatible with the version of SwiftProtobuf to which you are linking.\n// Please ensure that you are building against the same version of the API\n// that was used to generate this file.\nfileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {\n struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}\n typealias Version = _2\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_Stdio: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var stdinPort: Int32 {\n get {return _stdinPort ?? 0}\n set {_stdinPort = newValue}\n }\n /// Returns true if `stdinPort` has been explicitly set.\n public var hasStdinPort: Bool {return self._stdinPort != nil}\n /// Clears the value of `stdinPort`. Subsequent reads from it will return its default value.\n public mutating func clearStdinPort() {self._stdinPort = nil}\n\n public var stdoutPort: Int32 {\n get {return _stdoutPort ?? 0}\n set {_stdoutPort = newValue}\n }\n /// Returns true if `stdoutPort` has been explicitly set.\n public var hasStdoutPort: Bool {return self._stdoutPort != nil}\n /// Clears the value of `stdoutPort`. Subsequent reads from it will return its default value.\n public mutating func clearStdoutPort() {self._stdoutPort = nil}\n\n public var stderrPort: Int32 {\n get {return _stderrPort ?? 0}\n set {_stderrPort = newValue}\n }\n /// Returns true if `stderrPort` has been explicitly set.\n public var hasStderrPort: Bool {return self._stderrPort != nil}\n /// Clears the value of `stderrPort`. Subsequent reads from it will return its default value.\n public mutating func clearStderrPort() {self._stderrPort = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _stdinPort: Int32? = nil\n fileprivate var _stdoutPort: Int32? = nil\n fileprivate var _stderrPort: Int32? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var binaryPath: String = String()\n\n public var name: String = String()\n\n public var type: String = String()\n\n public var offset: String = String()\n\n public var magic: String = String()\n\n public var mask: String = String()\n\n public var flags: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetTimeRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var sec: Int64 = 0\n\n public var usec: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetTimeResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SysctlRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var settings: Dictionary = [:]\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SysctlResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var vsockPort: UInt32 = 0\n\n public var guestPath: String = String()\n\n public var guestSocketPermissions: UInt32 {\n get {return _guestSocketPermissions ?? 0}\n set {_guestSocketPermissions = newValue}\n }\n /// Returns true if `guestSocketPermissions` has been explicitly set.\n public var hasGuestSocketPermissions: Bool {return self._guestSocketPermissions != nil}\n /// Clears the value of `guestSocketPermissions`. Subsequent reads from it will return its default value.\n public mutating func clearGuestSocketPermissions() {self._guestSocketPermissions = nil}\n\n public var action: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest.Action = .into\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public enum Action: SwiftProtobuf.Enum, Swift.CaseIterable {\n public typealias RawValue = Int\n case into // = 0\n case outOf // = 1\n case UNRECOGNIZED(Int)\n\n public init() {\n self = .into\n }\n\n public init?(rawValue: Int) {\n switch rawValue {\n case 0: self = .into\n case 1: self = .outOf\n default: self = .UNRECOGNIZED(rawValue)\n }\n }\n\n public var rawValue: Int {\n switch self {\n case .into: return 0\n case .outOf: return 1\n case .UNRECOGNIZED(let i): return i\n }\n }\n\n // The compiler won't synthesize support with the UNRECOGNIZED case.\n public static let allCases: [Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest.Action] = [\n .into,\n .outOf,\n ]\n\n }\n\n public init() {}\n\n fileprivate var _guestSocketPermissions: UInt32? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_MountRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var type: String = String()\n\n public var source: String = String()\n\n public var destination: String = String()\n\n public var options: [String] = []\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_MountResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_UmountRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var path: String = String()\n\n public var flags: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_UmountResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetenvRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var key: String = String()\n\n public var value: String {\n get {return _value ?? String()}\n set {_value = newValue}\n }\n /// Returns true if `value` has been explicitly set.\n public var hasValue: Bool {return self._value != nil}\n /// Clears the value of `value`. Subsequent reads from it will return its default value.\n public mutating func clearValue() {self._value = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _value: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetenvResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_GetenvRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var key: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_GetenvResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var value: String {\n get {return _value ?? String()}\n set {_value = newValue}\n }\n /// Returns true if `value` has been explicitly set.\n public var hasValue: Bool {return self._value != nil}\n /// Clears the value of `value`. Subsequent reads from it will return its default value.\n public mutating func clearValue() {self._value = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _value: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var stdin: UInt32 {\n get {return _stdin ?? 0}\n set {_stdin = newValue}\n }\n /// Returns true if `stdin` has been explicitly set.\n public var hasStdin: Bool {return self._stdin != nil}\n /// Clears the value of `stdin`. Subsequent reads from it will return its default value.\n public mutating func clearStdin() {self._stdin = nil}\n\n public var stdout: UInt32 {\n get {return _stdout ?? 0}\n set {_stdout = newValue}\n }\n /// Returns true if `stdout` has been explicitly set.\n public var hasStdout: Bool {return self._stdout != nil}\n /// Clears the value of `stdout`. Subsequent reads from it will return its default value.\n public mutating func clearStdout() {self._stdout = nil}\n\n public var stderr: UInt32 {\n get {return _stderr ?? 0}\n set {_stderr = newValue}\n }\n /// Returns true if `stderr` has been explicitly set.\n public var hasStderr: Bool {return self._stderr != nil}\n /// Clears the value of `stderr`. Subsequent reads from it will return its default value.\n public mutating func clearStderr() {self._stderr = nil}\n\n public var configuration: Data = Data()\n\n public var options: Data {\n get {return _options ?? Data()}\n set {_options = newValue}\n }\n /// Returns true if `options` has been explicitly set.\n public var hasOptions: Bool {return self._options != nil}\n /// Clears the value of `options`. Subsequent reads from it will return its default value.\n public mutating func clearOptions() {self._options = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n fileprivate var _stdin: UInt32? = nil\n fileprivate var _stdout: UInt32? = nil\n fileprivate var _stderr: UInt32? = nil\n fileprivate var _options: Data? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var exitCode: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var rows: UInt32 = 0\n\n public var columns: UInt32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_StartProcessRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_StartProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var pid: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_KillProcessRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var signal: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_KillProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var result: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_MkdirRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var path: String = String()\n\n public var all: Bool = false\n\n public var perms: UInt32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_MkdirResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var interface: String = String()\n\n public var up: Bool = false\n\n public var mtu: UInt32 {\n get {return _mtu ?? 0}\n set {_mtu = newValue}\n }\n /// Returns true if `mtu` has been explicitly set.\n public var hasMtu: Bool {return self._mtu != nil}\n /// Clears the value of `mtu`. Subsequent reads from it will return its default value.\n public mutating func clearMtu() {self._mtu = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _mtu: UInt32? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var interface: String = String()\n\n public var address: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var interface: String = String()\n\n public var address: String = String()\n\n public var srcAddr: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var interface: String = String()\n\n public var gateway: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var location: String = String()\n\n public var nameservers: [String] = []\n\n public var domain: String {\n get {return _domain ?? String()}\n set {_domain = newValue}\n }\n /// Returns true if `domain` has been explicitly set.\n public var hasDomain: Bool {return self._domain != nil}\n /// Clears the value of `domain`. Subsequent reads from it will return its default value.\n public mutating func clearDomain() {self._domain = nil}\n\n public var searchDomains: [String] = []\n\n public var options: [String] = []\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _domain: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var location: String = String()\n\n public var entries: [Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.HostsEntry] = []\n\n public var comment: String {\n get {return _comment ?? String()}\n set {_comment = newValue}\n }\n /// Returns true if `comment` has been explicitly set.\n public var hasComment: Bool {return self._comment != nil}\n /// Clears the value of `comment`. Subsequent reads from it will return its default value.\n public mutating func clearComment() {self._comment = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public struct HostsEntry: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var ipAddress: String = String()\n\n public var hostnames: [String] = []\n\n public var comment: String {\n get {return _comment ?? String()}\n set {_comment = newValue}\n }\n /// Returns true if `comment` has been explicitly set.\n public var hasComment: Bool {return self._comment != nil}\n /// Clears the value of `comment`. Subsequent reads from it will return its default value.\n public mutating func clearComment() {self._comment = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _comment: String? = nil\n }\n\n public init() {}\n\n fileprivate var _comment: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SyncRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SyncResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_KillRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var pid: Int32 = 0\n\n public var signal: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_KillResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var result: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\n// MARK: - Code below here is support for the SwiftProtobuf runtime.\n\nfileprivate let _protobuf_package = \"com.apple.containerization.sandbox.v3\"\n\nextension Com_Apple_Containerization_Sandbox_V3_Stdio: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Stdio\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"stdinPort\"),\n 2: .same(proto: \"stdoutPort\"),\n 3: .same(proto: \"stderrPort\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self._stdinPort) }()\n case 2: try { try decoder.decodeSingularInt32Field(value: &self._stdoutPort) }()\n case 3: try { try decoder.decodeSingularInt32Field(value: &self._stderrPort) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n try { if let v = self._stdinPort {\n try visitor.visitSingularInt32Field(value: v, fieldNumber: 1)\n } }()\n try { if let v = self._stdoutPort {\n try visitor.visitSingularInt32Field(value: v, fieldNumber: 2)\n } }()\n try { if let v = self._stderrPort {\n try visitor.visitSingularInt32Field(value: v, fieldNumber: 3)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_Stdio, rhs: Com_Apple_Containerization_Sandbox_V3_Stdio) -> Bool {\n if lhs._stdinPort != rhs._stdinPort {return false}\n if lhs._stdoutPort != rhs._stdoutPort {return false}\n if lhs._stderrPort != rhs._stderrPort {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetupEmulatorRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"binary_path\"),\n 2: .same(proto: \"name\"),\n 3: .same(proto: \"type\"),\n 4: .same(proto: \"offset\"),\n 5: .same(proto: \"magic\"),\n 6: .same(proto: \"mask\"),\n 7: .same(proto: \"flags\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.binaryPath) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.name) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.type) }()\n case 4: try { try decoder.decodeSingularStringField(value: &self.offset) }()\n case 5: try { try decoder.decodeSingularStringField(value: &self.magic) }()\n case 6: try { try decoder.decodeSingularStringField(value: &self.mask) }()\n case 7: try { try decoder.decodeSingularStringField(value: &self.flags) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.binaryPath.isEmpty {\n try visitor.visitSingularStringField(value: self.binaryPath, fieldNumber: 1)\n }\n if !self.name.isEmpty {\n try visitor.visitSingularStringField(value: self.name, fieldNumber: 2)\n }\n if !self.type.isEmpty {\n try visitor.visitSingularStringField(value: self.type, fieldNumber: 3)\n }\n if !self.offset.isEmpty {\n try visitor.visitSingularStringField(value: self.offset, fieldNumber: 4)\n }\n if !self.magic.isEmpty {\n try visitor.visitSingularStringField(value: self.magic, fieldNumber: 5)\n }\n if !self.mask.isEmpty {\n try visitor.visitSingularStringField(value: self.mask, fieldNumber: 6)\n }\n if !self.flags.isEmpty {\n try visitor.visitSingularStringField(value: self.flags, fieldNumber: 7)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest, rhs: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest) -> Bool {\n if lhs.binaryPath != rhs.binaryPath {return false}\n if lhs.name != rhs.name {return false}\n if lhs.type != rhs.type {return false}\n if lhs.offset != rhs.offset {return false}\n if lhs.magic != rhs.magic {return false}\n if lhs.mask != rhs.mask {return false}\n if lhs.flags != rhs.flags {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetupEmulatorResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse, rhs: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetTimeRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetTimeRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"sec\"),\n 2: .same(proto: \"usec\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt64Field(value: &self.sec) }()\n case 2: try { try decoder.decodeSingularInt32Field(value: &self.usec) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.sec != 0 {\n try visitor.visitSingularInt64Field(value: self.sec, fieldNumber: 1)\n }\n if self.usec != 0 {\n try visitor.visitSingularInt32Field(value: self.usec, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest, rhs: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest) -> Bool {\n if lhs.sec != rhs.sec {return false}\n if lhs.usec != rhs.usec {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetTimeResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetTimeResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetTimeResponse, rhs: Com_Apple_Containerization_Sandbox_V3_SetTimeResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SysctlRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SysctlRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"settings\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.settings) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.settings.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.settings, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SysctlRequest, rhs: Com_Apple_Containerization_Sandbox_V3_SysctlRequest) -> Bool {\n if lhs.settings != rhs.settings {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SysctlResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SysctlResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SysctlResponse, rhs: Com_Apple_Containerization_Sandbox_V3_SysctlResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ProxyVsockRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .standard(proto: \"vsock_port\"),\n 3: .same(proto: \"guestPath\"),\n 4: .same(proto: \"guestSocketPermissions\"),\n 5: .same(proto: \"action\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularUInt32Field(value: &self.vsockPort) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.guestPath) }()\n case 4: try { try decoder.decodeSingularUInt32Field(value: &self._guestSocketPermissions) }()\n case 5: try { try decoder.decodeSingularEnumField(value: &self.action) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n if self.vsockPort != 0 {\n try visitor.visitSingularUInt32Field(value: self.vsockPort, fieldNumber: 2)\n }\n if !self.guestPath.isEmpty {\n try visitor.visitSingularStringField(value: self.guestPath, fieldNumber: 3)\n }\n try { if let v = self._guestSocketPermissions {\n try visitor.visitSingularUInt32Field(value: v, fieldNumber: 4)\n } }()\n if self.action != .into {\n try visitor.visitSingularEnumField(value: self.action, fieldNumber: 5)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest, rhs: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.vsockPort != rhs.vsockPort {return false}\n if lhs.guestPath != rhs.guestPath {return false}\n if lhs._guestSocketPermissions != rhs._guestSocketPermissions {return false}\n if lhs.action != rhs.action {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest.Action: SwiftProtobuf._ProtoNameProviding {\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 0: .same(proto: \"INTO\"),\n 1: .same(proto: \"OUT_OF\"),\n ]\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ProxyVsockResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse, rhs: Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".StopVsockProxyRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest, rhs: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".StopVsockProxyResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse, rhs: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_MountRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".MountRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"type\"),\n 2: .same(proto: \"source\"),\n 3: .same(proto: \"destination\"),\n 4: .same(proto: \"options\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.type) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.source) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.destination) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.options) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.type.isEmpty {\n try visitor.visitSingularStringField(value: self.type, fieldNumber: 1)\n }\n if !self.source.isEmpty {\n try visitor.visitSingularStringField(value: self.source, fieldNumber: 2)\n }\n if !self.destination.isEmpty {\n try visitor.visitSingularStringField(value: self.destination, fieldNumber: 3)\n }\n if !self.options.isEmpty {\n try visitor.visitRepeatedStringField(value: self.options, fieldNumber: 4)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_MountRequest, rhs: Com_Apple_Containerization_Sandbox_V3_MountRequest) -> Bool {\n if lhs.type != rhs.type {return false}\n if lhs.source != rhs.source {return false}\n if lhs.destination != rhs.destination {return false}\n if lhs.options != rhs.options {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_MountResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".MountResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_MountResponse, rhs: Com_Apple_Containerization_Sandbox_V3_MountResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_UmountRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".UmountRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"path\"),\n 2: .same(proto: \"flags\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.path) }()\n case 2: try { try decoder.decodeSingularInt32Field(value: &self.flags) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.path.isEmpty {\n try visitor.visitSingularStringField(value: self.path, fieldNumber: 1)\n }\n if self.flags != 0 {\n try visitor.visitSingularInt32Field(value: self.flags, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_UmountRequest, rhs: Com_Apple_Containerization_Sandbox_V3_UmountRequest) -> Bool {\n if lhs.path != rhs.path {return false}\n if lhs.flags != rhs.flags {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_UmountResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".UmountResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_UmountResponse, rhs: Com_Apple_Containerization_Sandbox_V3_UmountResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetenvRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetenvRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"key\"),\n 2: .same(proto: \"value\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.key) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._value) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.key.isEmpty {\n try visitor.visitSingularStringField(value: self.key, fieldNumber: 1)\n }\n try { if let v = self._value {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetenvRequest, rhs: Com_Apple_Containerization_Sandbox_V3_SetenvRequest) -> Bool {\n if lhs.key != rhs.key {return false}\n if lhs._value != rhs._value {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetenvResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetenvResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetenvResponse, rhs: Com_Apple_Containerization_Sandbox_V3_SetenvResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_GetenvRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".GetenvRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"key\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.key) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.key.isEmpty {\n try visitor.visitSingularStringField(value: self.key, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_GetenvRequest, rhs: Com_Apple_Containerization_Sandbox_V3_GetenvRequest) -> Bool {\n if lhs.key != rhs.key {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_GetenvResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".GetenvResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"value\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self._value) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n try { if let v = self._value {\n try visitor.visitSingularStringField(value: v, fieldNumber: 1)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_GetenvResponse, rhs: Com_Apple_Containerization_Sandbox_V3_GetenvResponse) -> Bool {\n if lhs._value != rhs._value {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CreateProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n 3: .same(proto: \"stdin\"),\n 4: .same(proto: \"stdout\"),\n 5: .same(proto: \"stderr\"),\n 6: .same(proto: \"configuration\"),\n 7: .same(proto: \"options\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n case 3: try { try decoder.decodeSingularUInt32Field(value: &self._stdin) }()\n case 4: try { try decoder.decodeSingularUInt32Field(value: &self._stdout) }()\n case 5: try { try decoder.decodeSingularUInt32Field(value: &self._stderr) }()\n case 6: try { try decoder.decodeSingularBytesField(value: &self.configuration) }()\n case 7: try { try decoder.decodeSingularBytesField(value: &self._options) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try { if let v = self._stdin {\n try visitor.visitSingularUInt32Field(value: v, fieldNumber: 3)\n } }()\n try { if let v = self._stdout {\n try visitor.visitSingularUInt32Field(value: v, fieldNumber: 4)\n } }()\n try { if let v = self._stderr {\n try visitor.visitSingularUInt32Field(value: v, fieldNumber: 5)\n } }()\n if !self.configuration.isEmpty {\n try visitor.visitSingularBytesField(value: self.configuration, fieldNumber: 6)\n }\n try { if let v = self._options {\n try visitor.visitSingularBytesField(value: v, fieldNumber: 7)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs._stdin != rhs._stdin {return false}\n if lhs._stdout != rhs._stdout {return false}\n if lhs._stderr != rhs._stderr {return false}\n if lhs.configuration != rhs.configuration {return false}\n if lhs._options != rhs._options {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CreateProcessResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".WaitProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".WaitProcessResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"exitCode\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.exitCode) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.exitCode != 0 {\n try visitor.visitSingularInt32Field(value: self.exitCode, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse) -> Bool {\n if lhs.exitCode != rhs.exitCode {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ResizeProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n 3: .same(proto: \"rows\"),\n 4: .same(proto: \"columns\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n case 3: try { try decoder.decodeSingularUInt32Field(value: &self.rows) }()\n case 4: try { try decoder.decodeSingularUInt32Field(value: &self.columns) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n if self.rows != 0 {\n try visitor.visitSingularUInt32Field(value: self.rows, fieldNumber: 3)\n }\n if self.columns != 0 {\n try visitor.visitSingularUInt32Field(value: self.columns, fieldNumber: 4)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.rows != rhs.rows {return false}\n if lhs.columns != rhs.columns {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ResizeProcessResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".DeleteProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".DeleteProcessResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_StartProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".StartProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_StartProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".StartProcessResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"pid\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.pid) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.pid != 0 {\n try visitor.visitSingularInt32Field(value: self.pid, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_StartProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_StartProcessResponse) -> Bool {\n if lhs.pid != rhs.pid {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_KillProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".KillProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n 3: .same(proto: \"signal\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n case 3: try { try decoder.decodeSingularInt32Field(value: &self.signal) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n if self.signal != 0 {\n try visitor.visitSingularInt32Field(value: self.signal, fieldNumber: 3)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.signal != rhs.signal {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_KillProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".KillProcessResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"result\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.result) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.result != 0 {\n try visitor.visitSingularInt32Field(value: self.result, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_KillProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_KillProcessResponse) -> Bool {\n if lhs.result != rhs.result {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CloseProcessStdinRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest, rhs: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CloseProcessStdinResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse, rhs: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_MkdirRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".MkdirRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"path\"),\n 2: .same(proto: \"all\"),\n 3: .same(proto: \"perms\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.path) }()\n case 2: try { try decoder.decodeSingularBoolField(value: &self.all) }()\n case 3: try { try decoder.decodeSingularUInt32Field(value: &self.perms) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.path.isEmpty {\n try visitor.visitSingularStringField(value: self.path, fieldNumber: 1)\n }\n if self.all != false {\n try visitor.visitSingularBoolField(value: self.all, fieldNumber: 2)\n }\n if self.perms != 0 {\n try visitor.visitSingularUInt32Field(value: self.perms, fieldNumber: 3)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_MkdirRequest, rhs: Com_Apple_Containerization_Sandbox_V3_MkdirRequest) -> Bool {\n if lhs.path != rhs.path {return false}\n if lhs.all != rhs.all {return false}\n if lhs.perms != rhs.perms {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_MkdirResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".MkdirResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_MkdirResponse, rhs: Com_Apple_Containerization_Sandbox_V3_MkdirResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpLinkSetRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"interface\"),\n 2: .same(proto: \"up\"),\n 3: .same(proto: \"mtu\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.interface) }()\n case 2: try { try decoder.decodeSingularBoolField(value: &self.up) }()\n case 3: try { try decoder.decodeSingularUInt32Field(value: &self._mtu) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.interface.isEmpty {\n try visitor.visitSingularStringField(value: self.interface, fieldNumber: 1)\n }\n if self.up != false {\n try visitor.visitSingularBoolField(value: self.up, fieldNumber: 2)\n }\n try { if let v = self._mtu {\n try visitor.visitSingularUInt32Field(value: v, fieldNumber: 3)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest, rhs: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest) -> Bool {\n if lhs.interface != rhs.interface {return false}\n if lhs.up != rhs.up {return false}\n if lhs._mtu != rhs._mtu {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpLinkSetResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse, rhs: Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpAddrAddRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"interface\"),\n 2: .same(proto: \"address\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.interface) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.address) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.interface.isEmpty {\n try visitor.visitSingularStringField(value: self.interface, fieldNumber: 1)\n }\n if !self.address.isEmpty {\n try visitor.visitSingularStringField(value: self.address, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest, rhs: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest) -> Bool {\n if lhs.interface != rhs.interface {return false}\n if lhs.address != rhs.address {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpAddrAddResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse, rhs: Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpRouteAddLinkRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"interface\"),\n 2: .same(proto: \"address\"),\n 3: .same(proto: \"srcAddr\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.interface) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.address) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.srcAddr) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.interface.isEmpty {\n try visitor.visitSingularStringField(value: self.interface, fieldNumber: 1)\n }\n if !self.address.isEmpty {\n try visitor.visitSingularStringField(value: self.address, fieldNumber: 2)\n }\n if !self.srcAddr.isEmpty {\n try visitor.visitSingularStringField(value: self.srcAddr, fieldNumber: 3)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest, rhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest) -> Bool {\n if lhs.interface != rhs.interface {return false}\n if lhs.address != rhs.address {return false}\n if lhs.srcAddr != rhs.srcAddr {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpRouteAddLinkResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse, rhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpRouteAddDefaultRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"interface\"),\n 2: .same(proto: \"gateway\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.interface) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.gateway) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.interface.isEmpty {\n try visitor.visitSingularStringField(value: self.interface, fieldNumber: 1)\n }\n if !self.gateway.isEmpty {\n try visitor.visitSingularStringField(value: self.gateway, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest, rhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest) -> Bool {\n if lhs.interface != rhs.interface {return false}\n if lhs.gateway != rhs.gateway {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpRouteAddDefaultResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse, rhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ConfigureDnsRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"location\"),\n 2: .same(proto: \"nameservers\"),\n 3: .same(proto: \"domain\"),\n 4: .same(proto: \"searchDomains\"),\n 5: .same(proto: \"options\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.location) }()\n case 2: try { try decoder.decodeRepeatedStringField(value: &self.nameservers) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self._domain) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.searchDomains) }()\n case 5: try { try decoder.decodeRepeatedStringField(value: &self.options) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.location.isEmpty {\n try visitor.visitSingularStringField(value: self.location, fieldNumber: 1)\n }\n if !self.nameservers.isEmpty {\n try visitor.visitRepeatedStringField(value: self.nameservers, fieldNumber: 2)\n }\n try { if let v = self._domain {\n try visitor.visitSingularStringField(value: v, fieldNumber: 3)\n } }()\n if !self.searchDomains.isEmpty {\n try visitor.visitRepeatedStringField(value: self.searchDomains, fieldNumber: 4)\n }\n if !self.options.isEmpty {\n try visitor.visitRepeatedStringField(value: self.options, fieldNumber: 5)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest, rhs: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest) -> Bool {\n if lhs.location != rhs.location {return false}\n if lhs.nameservers != rhs.nameservers {return false}\n if lhs._domain != rhs._domain {return false}\n if lhs.searchDomains != rhs.searchDomains {return false}\n if lhs.options != rhs.options {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ConfigureDnsResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse, rhs: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ConfigureHostsRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"location\"),\n 2: .same(proto: \"entries\"),\n 3: .same(proto: \"comment\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.location) }()\n case 2: try { try decoder.decodeRepeatedMessageField(value: &self.entries) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self._comment) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.location.isEmpty {\n try visitor.visitSingularStringField(value: self.location, fieldNumber: 1)\n }\n if !self.entries.isEmpty {\n try visitor.visitRepeatedMessageField(value: self.entries, fieldNumber: 2)\n }\n try { if let v = self._comment {\n try visitor.visitSingularStringField(value: v, fieldNumber: 3)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest, rhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest) -> Bool {\n if lhs.location != rhs.location {return false}\n if lhs.entries != rhs.entries {return false}\n if lhs._comment != rhs._comment {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.HostsEntry: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.protoMessageName + \".HostsEntry\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"ipAddress\"),\n 2: .same(proto: \"hostnames\"),\n 3: .same(proto: \"comment\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.ipAddress) }()\n case 2: try { try decoder.decodeRepeatedStringField(value: &self.hostnames) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self._comment) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.ipAddress.isEmpty {\n try visitor.visitSingularStringField(value: self.ipAddress, fieldNumber: 1)\n }\n if !self.hostnames.isEmpty {\n try visitor.visitRepeatedStringField(value: self.hostnames, fieldNumber: 2)\n }\n try { if let v = self._comment {\n try visitor.visitSingularStringField(value: v, fieldNumber: 3)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.HostsEntry, rhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.HostsEntry) -> Bool {\n if lhs.ipAddress != rhs.ipAddress {return false}\n if lhs.hostnames != rhs.hostnames {return false}\n if lhs._comment != rhs._comment {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ConfigureHostsResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse, rhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SyncRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SyncRequest\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SyncRequest, rhs: Com_Apple_Containerization_Sandbox_V3_SyncRequest) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SyncResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SyncResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SyncResponse, rhs: Com_Apple_Containerization_Sandbox_V3_SyncResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_KillRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".KillRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"pid\"),\n 3: .same(proto: \"signal\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.pid) }()\n case 3: try { try decoder.decodeSingularInt32Field(value: &self.signal) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.pid != 0 {\n try visitor.visitSingularInt32Field(value: self.pid, fieldNumber: 1)\n }\n if self.signal != 0 {\n try visitor.visitSingularInt32Field(value: self.signal, fieldNumber: 3)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_KillRequest, rhs: Com_Apple_Containerization_Sandbox_V3_KillRequest) -> Bool {\n if lhs.pid != rhs.pid {return false}\n if lhs.signal != rhs.signal {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_KillResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".KillResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"result\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.result) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.result != 0 {\n try visitor.visitSingularInt32Field(value: self.result, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_KillResponse, rhs: Com_Apple_Containerization_Sandbox_V3_KillResponse) -> Bool {\n if lhs.result != rhs.result {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n"], ["/containerization/Sources/cctl/LoginCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\nextension Application {\n struct Login: AsyncParsableCommand {\n\n static let configuration = CommandConfiguration(\n commandName: \"login\",\n abstract: \"Login to a registry\"\n )\n\n @OptionGroup() var application: Application\n\n @Option(name: .shortAndLong, help: \"Username\")\n var username: String = \"\"\n\n @Flag(help: \"Take the password from stdin\")\n var passwordStdin: Bool = false\n\n @Argument(help: \"Registry server name\")\n var server: String\n\n @Flag(help: \"Use plain text http to authenticate\") var http: Bool = false\n\n func run() async throws {\n var username = self.username\n var password = \"\"\n if passwordStdin {\n if username == \"\" {\n throw ContainerizationError(.invalidArgument, message: \"must provide --username with --password-stdin\")\n }\n guard let passwordData = try FileHandle.standardInput.readToEnd() else {\n throw ContainerizationError(.invalidArgument, message: \"failed to read password from stdin\")\n }\n password = String(decoding: passwordData, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)\n }\n let keychain = KeychainHelper(id: Application.keychainID)\n if username == \"\" {\n username = try keychain.userPrompt(domain: server)\n }\n if password == \"\" {\n password = try keychain.passwordPrompt()\n print()\n }\n\n let server = Reference.resolveDomain(domain: self.server)\n let scheme = http ? \"http\" : \"https\"\n let client = RegistryClient(\n host: server,\n scheme: scheme,\n authentication: BasicAuthentication(username: username, password: password),\n retryOptions: .init(\n maxRetries: 10,\n retryInterval: 300_000_000,\n shouldRetry: ({ response in\n response.status.code >= 500\n })\n )\n )\n try await client.ping()\n try keychain.save(domain: server, username: username, password: password)\n print(\"Login succeeded\")\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/IndexedAddressAllocator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Collections\nimport Synchronization\n\n/// Maps a network address to an array index value, or nil in the case of a domain error.\npackage typealias AddressToIndexTransform = @Sendable (AddressType) -> Int?\n\n/// Maps an array index value to a network address, or nil in the case of a domain error.\npackage typealias IndexToAddressTransform = @Sendable (Int) -> AddressType?\n\npackage final class IndexedAddressAllocator: AddressAllocator {\n private class State {\n var allocations: BitArray\n var enabled: Bool\n var allocationCount: Int\n let addressToIndex: AddressToIndexTransform\n let indexToAddress: IndexToAddressTransform\n\n init(\n size: Int,\n addressToIndex: @escaping AddressToIndexTransform,\n indexToAddress: @escaping IndexToAddressTransform\n ) {\n self.allocations = BitArray.init(repeating: false, count: size)\n self.enabled = true\n self.allocationCount = 0\n self.addressToIndex = addressToIndex\n self.indexToAddress = indexToAddress\n }\n }\n\n private let stateGuard: Mutex\n\n /// Create an allocator with specified size and index mappings.\n package init(\n size: Int,\n addressToIndex: @escaping AddressToIndexTransform,\n indexToAddress: @escaping IndexToAddressTransform\n ) {\n let state = State(\n size: size,\n addressToIndex: addressToIndex,\n indexToAddress: indexToAddress\n )\n self.stateGuard = Mutex(state)\n }\n\n public func allocate() throws -> AddressType {\n try self.stateGuard.withLock { state in\n guard state.enabled else {\n throw AllocatorError.allocatorDisabled\n }\n\n guard let index = state.allocations.firstIndex(of: false) else {\n throw AllocatorError.allocatorFull\n }\n\n guard let address = state.indexToAddress(index) else {\n throw AllocatorError.invalidIndex(index)\n }\n\n state.allocations[index] = true\n state.allocationCount += 1\n return address\n }\n }\n\n package func reserve(_ address: AddressType) throws {\n try self.stateGuard.withLock { state in\n guard state.enabled else {\n throw AllocatorError.allocatorDisabled\n }\n\n guard let index = state.addressToIndex(address) else {\n throw AllocatorError.invalidAddress(address.description)\n }\n\n guard !state.allocations[index] else {\n throw AllocatorError.alreadyAllocated(\"\\(address.description)\")\n }\n\n state.allocations[index] = true\n state.allocationCount += 1\n }\n\n }\n\n package func release(_ address: AddressType) throws {\n try self.stateGuard.withLock { state in\n guard let index = state.addressToIndex(address) else {\n throw AllocatorError.invalidAddress(address.description)\n }\n\n guard state.allocations[index] else {\n throw AllocatorError.notAllocated(\"\\(address.description)\")\n }\n\n state.allocations[index] = false\n state.allocationCount -= 1\n }\n }\n\n package func disableAllocator() -> Bool {\n self.stateGuard.withLock { state in\n guard state.allocationCount == 0 else {\n return false\n }\n state.enabled = false\n return true\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/ArchiveWriterConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CArchive\n\n/// Represents the configuration settings for an `ArchiveWriter`.\n///\n/// This struct allows specifying the archive format, compression filter,\n/// various format-specific options, and preferred locales for string encoding.\npublic struct ArchiveWriterConfiguration {\n /// The desired archive format\n public var format: Format\n /// The compression filter to apply to the archive\n public var filter: Filter\n /// An array of format-specific options to apply to the archive.\n /// This includes options like compression level and extended attribute format.\n public var options: [Options]\n /// An array of preferred locale identifiers for string encoding\n public var locales: [String]\n\n /// Initializes a new `ArchiveWriterConfiguration`.\n ///\n /// Sets up the configuration with the specified format, filter, options, and locales.\n public init(\n format: Format, filter: Filter, options: [Options] = [], locales: [String] = [\"en_US.UTF-8\", \"C.UTF-8\"]\n ) {\n self.format = format\n self.filter = filter\n self.options = options\n self.locales = locales\n }\n}\n\nextension ArchiveWriter {\n internal func setFormat(_ format: Format) throws {\n guard let underlying = self.underlying else { throw ArchiveError.noUnderlyingArchive }\n let r = archive_write_set_format(underlying, format.code)\n guard r == ARCHIVE_OK else { throw ArchiveError.unableToSetFormat(r, format) }\n }\n\n internal func addFilter(_ filter: Filter) throws {\n guard let underlying = self.underlying else { throw ArchiveError.noUnderlyingArchive }\n let r = archive_write_add_filter(underlying, filter.code)\n guard r == ARCHIVE_OK else { throw ArchiveError.unableToAddFilter(r, filter) }\n }\n\n internal func setOptions(_ options: [Options]) throws {\n try options.forEach {\n switch $0 {\n case .compressionLevel(let level):\n try wrap(\n archive_write_set_option(underlying, nil, \"compression-level\", \"\\(level)\"),\n ArchiveError.unableToSetOption, underlying: self.underlying)\n case .compression(.store):\n try wrap(\n archive_write_set_option(underlying, nil, \"compression\", \"store\"), ArchiveError.unableToSetOption,\n underlying: self.underlying)\n case .compression(.deflate):\n try wrap(\n archive_write_set_option(underlying, nil, \"compression\", \"deflate\"), ArchiveError.unableToSetOption,\n underlying: self.underlying)\n case .xattrformat(let value):\n let v = value.description\n try wrap(\n archive_write_set_option(underlying, nil, \"xattrheader\", v), ArchiveError.unableToSetOption,\n underlying: self.underlying)\n }\n }\n }\n}\n\npublic enum Options {\n case compressionLevel(UInt32)\n case compression(Compression)\n case xattrformat(XattrFormat)\n\n public enum Compression {\n case store\n case deflate\n }\n\n public enum XattrFormat: String, CustomStringConvertible {\n case schily\n case libarchive\n case all\n\n public var description: String {\n switch self {\n case .libarchive:\n return \"LIBARCHIVE\"\n case .schily:\n return \"SCHILY\"\n case .all:\n return \"ALL\"\n }\n }\n }\n}\n\n/// An enumeration of the supported archive formats.\npublic enum Format: String, Sendable {\n /// POSIX-standard `ustar` archives\n case ustar\n case gnutar\n /// POSIX `pax interchange format` archives\n case pax\n case paxRestricted\n /// POSIX octet-oriented cpio archives\n case cpio\n case cpioNewc\n /// Zip archive\n case zip\n /// two different variants of shar archives\n case shar\n case sharDump\n /// ISO9660 CD images\n case iso9660\n /// 7-Zip archives\n case sevenZip\n /// ar archives\n case arBSD\n case arGNU\n /// mtree file tree descriptions\n case mtree\n /// XAR archives\n case xar\n\n internal var code: CInt {\n switch self {\n case .ustar: return ARCHIVE_FORMAT_TAR_USTAR\n case .pax: return ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE\n case .paxRestricted: return ARCHIVE_FORMAT_TAR_PAX_RESTRICTED\n case .gnutar: return ARCHIVE_FORMAT_TAR_GNUTAR\n case .cpio: return ARCHIVE_FORMAT_CPIO_POSIX\n case .cpioNewc: return ARCHIVE_FORMAT_CPIO_AFIO_LARGE\n case .zip: return ARCHIVE_FORMAT_ZIP\n case .shar: return ARCHIVE_FORMAT_SHAR_BASE\n case .sharDump: return ARCHIVE_FORMAT_SHAR_DUMP\n case .iso9660: return ARCHIVE_FORMAT_ISO9660\n case .sevenZip: return ARCHIVE_FORMAT_7ZIP\n case .arBSD: return ARCHIVE_FORMAT_AR_BSD\n case .arGNU: return ARCHIVE_FORMAT_AR_GNU\n case .mtree: return ARCHIVE_FORMAT_MTREE\n case .xar: return ARCHIVE_FORMAT_XAR\n }\n }\n}\n\n/// An enumeration of the supported filters (compression / encoding standards) for an archive.\npublic enum Filter: String, Sendable {\n case none\n case gzip\n case bzip2\n case compress\n case lzma\n case xz\n case uu\n case rpm\n case lzip\n case lrzip\n case lzop\n case grzip\n case lz4\n\n internal var code: CInt {\n switch self {\n case .none: return ARCHIVE_FILTER_NONE\n case .gzip: return ARCHIVE_FILTER_GZIP\n case .bzip2: return ARCHIVE_FILTER_BZIP2\n case .compress: return ARCHIVE_FILTER_COMPRESS\n case .lzma: return ARCHIVE_FILTER_LZMA\n case .xz: return ARCHIVE_FILTER_XZ\n case .uu: return ARCHIVE_FILTER_UU\n case .rpm: return ARCHIVE_FILTER_RPM\n case .lzip: return ARCHIVE_FILTER_LZIP\n case .lrzip: return ARCHIVE_FILTER_LRZIP\n case .lzop: return ARCHIVE_FILTER_LZOP\n case .grzip: return ARCHIVE_FILTER_GRZIP\n case .lz4: return ARCHIVE_FILTER_LZ4\n }\n }\n}\n"], ["/containerization/Sources/Containerization/VZVirtualMachineManager.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport Logging\n\n/// A virtualization.framework backed `VirtualMachineManager` implementation.\npublic struct VZVirtualMachineManager: VirtualMachineManager {\n private let kernel: Kernel\n private let bootlog: String?\n private let initialFilesystem: Mount\n private let logger: Logger?\n\n public init(\n kernel: Kernel,\n initialFilesystem: Mount,\n bootlog: String? = nil,\n logger: Logger? = nil\n ) {\n self.kernel = kernel\n self.bootlog = bootlog\n self.initialFilesystem = initialFilesystem\n self.logger = logger\n }\n\n public func create(container: Container) throws -> any VirtualMachineInstance {\n guard let c = container as? LinuxContainer else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"provided container is not a LinuxContainer\"\n )\n }\n\n return try VZVirtualMachineInstance(\n logger: self.logger,\n with: { config in\n config.cpus = container.cpus\n config.memoryInBytes = container.memoryInBytes\n\n config.kernel = self.kernel\n config.initialFilesystem = self.initialFilesystem\n\n config.interfaces = container.interfaces\n if let bootlog {\n config.bootlog = URL(filePath: bootlog)\n }\n config.rosetta = c.config.rosetta\n config.nestedVirtualization = c.config.virtualization\n\n config.mounts = [c.rootfs] + c.config.mounts\n })\n }\n}\n#endif\n"], ["/containerization/Sources/ContainerizationOS/File.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Trivial type to discover information about a given file (uid, gid, mode...).\npublic struct File: Sendable {\n /// `File` errors.\n public enum Error: Swift.Error, CustomStringConvertible {\n case errno(_ e: Int32)\n\n public var description: String {\n switch self {\n case .errno(let code):\n return \"errno \\(code)\"\n }\n }\n }\n\n /// Returns a `FileInfo` struct with information about the file.\n /// - Parameters:\n /// - url: The path to the file.\n public static func info(_ url: URL) throws -> FileInfo {\n try info(url.path)\n }\n\n /// Returns a `FileInfo` struct with information about the file.\n /// - Parameters:\n /// - path: The path to the file as a string.\n public static func info(_ path: String) throws -> FileInfo {\n var st = stat()\n guard stat(path, &st) == 0 else {\n throw Error.errno(errno)\n }\n return FileInfo(path, stat: st)\n }\n}\n\n/// `FileInfo` holds and provides easy access to stat(2) data\n/// for a file.\npublic struct FileInfo: Sendable {\n private let _stat_t: Foundation.stat\n private let _path: String\n\n init(_ path: String, stat: stat) {\n self._path = path\n self._stat_t = stat\n }\n\n /// mode_t for the file.\n public var mode: mode_t {\n self._stat_t.st_mode\n }\n\n /// The files uid.\n public var uid: Int {\n Int(self._stat_t.st_uid)\n }\n\n /// The files gid.\n public var gid: Int {\n Int(self._stat_t.st_gid)\n }\n\n /// The filesystem ID the file belongs to.\n public var dev: Int {\n Int(self._stat_t.st_dev)\n }\n\n /// The files inode number.\n public var ino: Int {\n Int(self._stat_t.st_ino)\n }\n\n /// The size of the file.\n public var size: Int {\n Int(self._stat_t.st_size)\n }\n\n /// The path to the file.\n public var path: String {\n self._path\n }\n\n /// Returns if the file is a directory.\n public var isDirectory: Bool {\n mode & S_IFMT == S_IFDIR\n }\n\n /// Returns if the file is a pipe.\n public var isPipe: Bool {\n mode & S_IFMT == S_IFIFO\n }\n\n /// Returns if the file is a socket.\n public var isSocket: Bool {\n mode & S_IFMT == S_IFSOCK\n }\n\n /// Returns if the file is a link.\n public var isLink: Bool {\n mode & S_IFMT == S_IFLNK\n }\n\n /// Returns if the file is a regular file.\n public var isRegularFile: Bool {\n mode & S_IFMT == S_IFREG\n }\n\n /// Returns if the file is a block device.\n public var isBlock: Bool {\n mode & S_IFMT == S_IFBLK\n }\n\n /// Returns if the file is a character device.\n public var isChar: Bool {\n mode & S_IFMT == S_IFCHR\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Linux/Binfmt.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n#if canImport(Musl)\nimport Musl\nprivate let _mount = Musl.mount\n#elseif canImport(Glibc)\nimport Glibc\nprivate let _mount = Glibc.mount\n#endif\n\n/// `Binfmt` is a utility type that contains static helpers and types for\n/// mounting the Linux binfmt_misc filesystem, and creating new binfmt entries.\npublic struct Binfmt: Sendable {\n /// Default mount path for binfmt_misc.\n public static let path = \"/proc/sys/fs/binfmt_misc\"\n\n /// Entry models a binfmt_misc entry.\n /// https://docs.kernel.org/admin-guide/binfmt-misc.html\n public struct Entry {\n public var name: String\n public var type: String\n public var offset: String\n public var magic: String\n public var mask: String\n public var flags: String\n\n public init(\n name: String,\n type: String = \"M\",\n offset: String = \"\",\n magic: String,\n mask: String,\n flags: String = \"CF\"\n ) {\n self.name = name\n self.type = type\n self.offset = offset\n self.magic = magic\n self.mask = mask\n self.flags = flags\n }\n\n /// Returns a binfmt `Entry` for amd64 ELF binaries.\n public static func amd64() -> Self {\n Binfmt.Entry(\n name: \"x86_64\",\n magic: #\"\\x7fELF\\x02\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x3e\\x00\"#,\n mask: #\"\\xff\\xff\\xff\\xff\\xff\\xfe\\xfe\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff\"#\n )\n }\n\n #if os(Linux)\n /// Register the passed in `binaryPath` as the interpreter for a new binfmt_misc entry.\n public func register(binaryPath: String) throws {\n let registration = \":\\(self.name):\\(self.type):\\(self.offset):\\(self.magic):\\(self.mask):\\(binaryPath):\\(self.flags)\"\n\n try registration.write(\n to: URL(fileURLWithPath: Binfmt.path).appendingPathComponent(\"register\"),\n atomically: false,\n encoding: .ascii\n )\n }\n\n /// Deregister the binfmt_misc entry described by the current object.\n public func deregister() throws {\n let data = \"-1\"\n try data.write(\n to: URL(fileURLWithPath: Binfmt.path).appendingPathComponent(self.name),\n atomically: false,\n encoding: .ascii\n )\n }\n #endif // os(Linux)\n }\n\n #if os(Linux)\n /// Crude check to see if /proc/sys/fs/binfmt_misc/register exists.\n public static func mounted() -> Bool {\n FileManager.default.fileExists(atPath: \"\\(Self.path)/register\")\n }\n\n /// Mount the binfmt_misc filesystem.\n public static func mount() throws {\n guard _mount(\"binfmt_misc\", Self.path, \"binfmt_misc\", 0, \"\") == 0 else {\n throw POSIXError.fromErrno()\n }\n }\n #endif // os(Linux)\n}\n"], ["/containerization/Sources/cctl/RootfsCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationEXT4\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\n\nextension Application {\n struct Rootfs: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"rootfs\",\n abstract: \"Manage the root filesystem for a container\",\n subcommands: [\n Create.self\n ]\n )\n\n struct Create: AsyncParsableCommand {\n @Option(name: .long, help: \"Path to vminitd\")\n var vminitd: String\n\n @Option(name: .long, help: \"Path to vmexec\")\n var vmexec: String\n\n @Option(name: .long, help: \"Platform of the built binaries being packaged into the block\")\n var platformString: String = Platform.current.description\n\n @Option(name: .long, help: \"Labels to add to the built image of the form =, [=,...]\")\n var labels: [String] = []\n\n @Argument var rootfsPath: String\n\n @Argument var tag: String\n\n private static let directories = [\n \"bin\",\n \"sbin\",\n \"dev\",\n \"sys\",\n \"proc/self\", // hack for swift init's booting\n \"run\",\n \"tmp\",\n \"mnt\",\n \"var\",\n ]\n\n func run() async throws {\n try await writeArchive()\n let p = try Platform(from: platformString)\n let rootfs = URL(filePath: rootfsPath)\n let labels = Application.parseKeyValuePairs(from: labels)\n _ = try await InitImage.create(\n reference: tag, rootfs: rootfs,\n platform: p, labels: labels,\n imageStore: Application.imageStore,\n contentStore: Application.contentStore)\n }\n\n private func writeArchive() async throws {\n let writer = try ArchiveWriter(format: .pax, filter: .gzip, file: URL(filePath: rootfsPath))\n let ts = Date()\n let entry = WriteEntry()\n entry.permissions = 0o755\n entry.modificationDate = ts\n entry.creationDate = ts\n entry.group = 0\n entry.owner = 0\n entry.fileType = .directory\n // create the initial directory structure.\n for dir in Self.directories {\n entry.path = dir\n try writer.writeEntry(entry: entry, data: nil)\n }\n\n entry.fileType = .regular\n entry.path = \"sbin/vminitd\"\n\n var src = URL(fileURLWithPath: vminitd)\n var data = try Data(contentsOf: src)\n entry.size = Int64(data.count)\n try writer.writeEntry(entry: entry, data: data)\n\n src = URL(fileURLWithPath: vmexec)\n data = try Data(contentsOf: src)\n entry.path = \"sbin/vmexec\"\n entry.size = Int64(data.count)\n try writer.writeEntry(entry: entry, data: data)\n\n entry.fileType = .symbolicLink\n entry.path = \"proc/self/exe\"\n entry.symlinkTarget = \"sbin/vminitd\"\n entry.size = nil\n try writer.writeEntry(entry: entry, data: data)\n try writer.finishEncoding()\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Bundle.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\n\n#if canImport(Musl)\nimport Musl\nprivate let _mount = Musl.mount\nprivate let _umount = Musl.umount2\n#elseif canImport(Glibc)\nimport Glibc\nprivate let _mount = Glibc.mount\nprivate let _umount = Glibc.umount2\n#endif\n\n/// `Bundle` represents an OCI runtime spec bundle for running\n/// a container.\npublic struct Bundle: Sendable {\n /// The path to the bundle.\n public let path: URL\n\n /// The path to the OCI runtime spec config.json file.\n public var configPath: URL {\n self.path.appending(path: \"config.json\")\n }\n\n /// The path to a rootfs mount inside the bundle.\n public var rootfsPath: URL {\n self.path.appending(path: \"rootfs\")\n }\n\n /// Create the OCI bundle.\n ///\n /// - Parameters:\n /// - path: A URL pointing to where to create the bundle on the filesystem.\n /// - spec: A data blob that should contain an OCI runtime spec. This will be written\n /// to the bundle as a \"config.json\" file.\n public static func create(path: URL, spec: Data) throws -> Bundle {\n try self.init(path: path, spec: spec)\n }\n\n /// Create the OCI bundle.\n ///\n /// - Parameters:\n /// - path: A URL pointing to where to create the bundle on the filesystem.\n /// - spec: An OCI runtime spec that will be written to the bundle as a \"config.json\"\n /// file.\n public static func create(path: URL, spec: ContainerizationOCI.Spec) throws -> Bundle {\n try self.init(path: path, spec: spec)\n }\n\n /// Load an OCI bundle from the provided path.\n ///\n /// - Parameters:\n /// - path: A URL pointing to where to load the bundle from on the filesystem.\n public static func load(path: URL) throws -> Bundle {\n try self.init(path: path)\n }\n\n private init(path: URL) throws {\n let fm = FileManager.default\n if !fm.fileExists(atPath: path.path) {\n throw ContainerizationError(.invalidArgument, message: \"no bundle at \\(path.path)\")\n }\n self.path = path\n }\n\n // This constructor does not do any validation that data is actually a\n // valid OCI spec.\n private init(path: URL, spec: Data) throws {\n self.path = path\n\n let fm = FileManager.default\n try fm.createDirectory(\n atPath: self.path.appending(component: \"rootfs\").path,\n withIntermediateDirectories: true\n )\n\n try spec.write(to: self.configPath)\n }\n\n private init(path: URL, spec: ContainerizationOCI.Spec) throws {\n self.path = path\n\n let fm = FileManager.default\n try fm.createDirectory(\n atPath: self.path.appending(component: \"rootfs\").path,\n withIntermediateDirectories: true\n )\n\n let specData = try JSONEncoder().encode(spec)\n try specData.write(to: self.configPath)\n }\n\n /// Delete the OCI bundle from the filesystem.\n public func delete() throws {\n // Unmount, and then blow away the dir.\n #if os(Linux)\n let rootfs = self.rootfsPath.path\n guard _umount(rootfs, 0) == 0 else {\n throw POSIXError.fromErrno()\n }\n #endif\n // removeItem is recursive so should blow away the rootfs dir inside as well.\n let fm = FileManager.default\n try fm.removeItem(at: self.path)\n }\n\n /// Load and return the OCI runtime spec written to the bundle.\n public func loadConfig() throws -> ContainerizationOCI.Spec {\n let data = try Data(contentsOf: self.configPath)\n return try JSONDecoder().decode(ContainerizationOCI.Spec.self, from: data)\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/RotatingAddressAllocator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Synchronization\n\npackage final class RotatingAddressAllocator: AddressAllocator {\n package typealias AddressType = UInt32\n\n private struct State {\n var allocations: [AddressType]\n var enabled: Bool\n var allocationCount: Int\n let addressToIndex: AddressToIndexTransform\n let indexToAddress: IndexToAddressTransform\n\n init(\n size: UInt32,\n addressToIndex: @escaping AddressToIndexTransform,\n indexToAddress: @escaping IndexToAddressTransform\n ) {\n self.allocations = [UInt32](0..\n\n /// Create an allocator with specified size and index mappings.\n package init(\n size: UInt32,\n addressToIndex: @escaping AddressToIndexTransform,\n indexToAddress: @escaping IndexToAddressTransform\n ) {\n let state = State(\n size: size,\n addressToIndex: addressToIndex,\n indexToAddress: indexToAddress\n )\n self.stateGuard = Mutex(state)\n }\n\n public func allocate() throws -> AddressType {\n try self.stateGuard.withLock { state in\n guard state.enabled else {\n throw AllocatorError.allocatorDisabled\n }\n\n guard state.allocations.count > 0 else {\n throw AllocatorError.allocatorFull\n }\n\n let value = state.allocations.removeFirst()\n\n guard let address = state.indexToAddress(Int(value)) else {\n throw AllocatorError.invalidIndex(Int(value))\n }\n\n state.allocationCount += 1\n return address\n }\n }\n\n package func reserve(_ address: AddressType) throws {\n try self.stateGuard.withLock { state in\n guard state.enabled else {\n throw AllocatorError.allocatorDisabled\n }\n\n guard let index = state.addressToIndex(address) else {\n throw AllocatorError.invalidAddress(address.description)\n }\n\n let i = state.allocations.firstIndex(of: UInt32(index))\n guard let i else {\n throw AllocatorError.alreadyAllocated(\"\\(address.description)\")\n }\n\n _ = state.allocations.remove(at: i)\n state.allocationCount += 1\n }\n }\n\n package func release(_ address: AddressType) throws {\n try self.stateGuard.withLock { state in\n guard let index = (state.addressToIndex(address)) else {\n throw AllocatorError.invalidAddress(address.description)\n }\n let value = UInt32(index)\n\n guard !state.allocations.contains(value) else {\n throw AllocatorError.notAllocated(\"\\(address.description)\")\n }\n\n state.allocations.append(value)\n state.allocationCount -= 1\n }\n }\n\n package func disableAllocator() -> Bool {\n self.stateGuard.withLock { state in\n guard state.allocationCount == 0 else {\n return false\n }\n state.enabled = false\n return true\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Reference.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\n\nprivate let referenceTotalLengthMax = 255\nprivate let nameTotalLengthMax = 127\nprivate let legacyDockerRegistryHost = \"docker.io\"\nprivate let dockerRegistryHost = \"registry-1.docker.io\"\nprivate let defaultDockerRegistryRepo = \"library\"\nprivate let defaultTag = \"latest\"\n\n/// A Reference is composed of the various parts of an OCI image reference.\n/// For example:\n/// let imageReference = \"my-registry.com/repository/image:tag2\"\n/// let reference = Reference.parse(imageReference)\n/// print(reference.domain!) // gives us \"my-registry.com\"\n/// print(reference.name) // gives us \"my-registry.com/repository/image\"\n/// print(reference.path) // gives us \"repository/image\"\n/// print(reference.tag!) // gives us \"tag2\"\n/// print(reference.digest) // gives us \"nil\"\npublic class Reference: CustomStringConvertible {\n private var _domain: String?\n public var domain: String? {\n _domain\n }\n public var resolvedDomain: String? {\n if let d = _domain {\n return Self.resolveDomain(domain: d)\n }\n return nil\n }\n\n private var _path: String\n public var path: String {\n _path\n }\n\n private var _tag: String?\n public var tag: String? {\n _tag\n }\n\n private var _digest: String?\n public var digest: String? {\n _digest\n }\n\n public var name: String {\n if let domain, !domain.isEmpty {\n return \"\\(domain)/\\(path)\"\n }\n return path\n }\n\n public var description: String {\n if let tag {\n return \"\\(name):\\(tag)\"\n }\n if let digest {\n return \"\\(name)@\\(digest)\"\n }\n return name\n }\n\n static let identifierPattern = \"([a-f0-9]{64})\"\n\n static let domainPattern = {\n let domainNameComponent = \"(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])\"\n let optionalPort = \"(?::[0-9]+)?\"\n let ipv6address = \"\\\\[(?:[a-fA-F0-9:]+)\\\\]\"\n let domainName = \"\\(domainNameComponent)(?:\\\\.\\(domainNameComponent))*\"\n let host = \"(?:\\(domainName)|\\(ipv6address))\"\n let domainAndPort = \"\\(host)\\(optionalPort)\"\n return domainAndPort\n }()\n\n static let pathPattern = \"(?(?:[a-z0-9]+(?:[._]|__|-|/)?)*[a-z0-9]+)\"\n static let tagPattern = \"(?::(?[\\\\w][\\\\w.-]{0,127}))?(?:@(?sha256:[0-9a-fA-F]{64}))?\"\n static let pathTagPattern = \"\\(pathPattern)\\(tagPattern)\"\n\n public init(path: String, domain: String? = nil, tag: String? = nil, digest: String? = nil) throws {\n if let domain, !domain.isEmpty {\n self._domain = domain\n }\n\n self._path = path\n self._tag = tag\n self._digest = digest\n }\n\n public static func parse(_ s: String) throws -> Reference {\n if s.count > referenceTotalLengthMax {\n throw ContainerizationError(.invalidArgument, message: \"Reference length \\(s.count) greater than \\(referenceTotalLengthMax)\")\n }\n\n let identifierRegex = try Regex(Self.identifierPattern)\n guard try identifierRegex.wholeMatch(in: s) == nil else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot specify 64 byte hex string as reference\")\n }\n\n let (domain, remainder) = try Self.parseDomain(from: s)\n let constructedRawReference: String = remainder\n if let domain {\n let domainRegex = try Regex(domainPattern)\n guard try domainRegex.wholeMatch(in: domain) != nil else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid domain \\(domain) for reference \\(s)\")\n }\n }\n let fields = try constructedRawReference.matches(regex: pathTagPattern)\n guard let path = fields[\"path\"] else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot parse path for reference \\(s)\")\n }\n\n let ref = try Reference(path: path, domain: domain)\n if ref.name.count > nameTotalLengthMax {\n throw ContainerizationError(.invalidArgument, message: \"Repo length \\(ref.name.count) greater than \\(nameTotalLengthMax)\")\n }\n\n // Extract tag and digest\n let tag = fields[\"tag\"] ?? \"\"\n let digest = fields[\"digest\"] ?? \"\"\n\n if !digest.isEmpty {\n return try ref.withDigest(digest)\n } else if !tag.isEmpty {\n return try ref.withTag(tag)\n }\n return ref\n }\n\n private static func parseDomain(from s: String) throws -> (domain: String?, remainder: String) {\n var domain: String? = nil\n var path: String = s\n let charset = CharacterSet(charactersIn: \".:\")\n let splits = s.split(separator: \"/\", maxSplits: 1)\n guard splits.count == 2 else {\n if s.starts(with: \"localhost\") {\n return (s, \"\")\n }\n return (nil, s)\n }\n let _domain = String(splits[0])\n let _path = String(splits[1])\n if _domain.starts(with: \"localhost\") || _domain.rangeOfCharacter(from: charset) != nil {\n domain = _domain\n path = _path\n }\n return (domain, path)\n }\n\n public static func withName(_ name: String) throws -> Reference {\n if name.count > nameTotalLengthMax {\n throw ContainerizationError(.invalidArgument, message: \"Name length \\(name.count) greater than \\(nameTotalLengthMax)\")\n }\n let fields = try name.matches(regex: Self.domainPattern)\n // Extract domain and path\n let domain = fields[\"domain\"] ?? \"\"\n let path = fields[\"path\"] ?? \"\"\n\n if domain.isEmpty || path.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Image reference domain or path is empty\")\n }\n\n return try Reference(path: path, domain: domain)\n }\n\n public func withTag(_ tag: String) throws -> Reference {\n var tag = tag\n if !tag.starts(with: \":\") {\n tag = \":\" + tag\n }\n let fields = try tag.matches(regex: Self.tagPattern)\n tag = fields[\"tag\"] ?? \"\"\n\n if tag.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Invalid format for image reference. Missing tag\")\n }\n return try Reference(path: self.path, domain: self.domain, tag: tag)\n }\n\n public func withDigest(_ digest: String) throws -> Reference {\n var digest = digest\n if !digest.starts(with: \"@\") {\n digest = \"@\" + digest\n }\n let fields = try digest.matches(regex: Self.tagPattern)\n digest = fields[\"digest\"] ?? \"\"\n\n if digest.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Invalid format for image reference. Missing digest\")\n }\n return try Reference(path: self.path, domain: self.domain, digest: digest)\n }\n\n private static func splitDomain(_ name: String) -> (domain: String, path: String) {\n let parts = name.split(separator: \"/\")\n guard parts.count == 2 else {\n return (\"\", name)\n }\n return (String(parts[0]), String(parts[1]))\n }\n\n /// Normalize the reference object.\n /// Normalization is useful in cases where the reference object is to be used to\n /// fetch/push an image from/to a remote registry.\n /// It does the following:\n /// - Adds a default tag of \"latest\" if the reference had no tag/digest set.\n /// - If the domain is \"registry-1.docker.io\" or \"docker.io\" and the path has no repository set,\n /// it adds a default \"library/\" repository name.\n public func normalize() {\n if let domain = self.domain, domain == dockerRegistryHost || domain == legacyDockerRegistryHost {\n // Check if the image is being referenced by a named tag.\n // If it is, and a repository is not specified, prefix it with \"library/\".\n // This needs to be done only if we are using the Docker registry.\n if !self.path.contains(\"/\") {\n self._path = \"\\(defaultDockerRegistryRepo)/\\(self._path)\"\n }\n }\n let identifier = self._tag ?? self._digest\n if identifier == nil {\n // If the user did not specify a tag or a digest for the reference, set the tag to \"latest\".\n self._tag = defaultTag\n }\n }\n\n public static func resolveDomain(domain: String) -> String {\n if domain == legacyDockerRegistryHost {\n return dockerRegistryHost\n }\n return domain\n }\n}\n\nextension String {\n func matches(regex: String) throws -> [String: String] {\n do {\n let regex = try NSRegularExpression(pattern: regex, options: [])\n let nsRange = NSRange(self.startIndex.. [String] {\n let pattern = self.pattern\n let regex = try NSRegularExpression(pattern: \"\\\\(\\\\?<(\\\\w+)>\", options: [])\n let nsRange = NSRange(pattern.startIndex.. Authentication {\n let kq = KeychainQuery()\n\n do {\n guard let fetched = try kq.get(id: self.id, host: domain) else {\n throw Self.Error.keyNotFound\n }\n return BasicAuthentication(\n username: fetched.account,\n password: fetched.data\n )\n } catch let err as KeychainQuery.Error {\n switch err {\n case .keyNotPresent(_):\n throw Self.Error.keyNotFound\n default:\n throw Self.Error.queryError(\"query failure: \\(String(describing: err))\")\n }\n }\n }\n\n /// Delete authorization data for a given domain from the keychain.\n public func delete(domain: String) throws {\n let kq = KeychainQuery()\n try kq.delete(id: self.id, host: domain)\n }\n\n /// Save authorization data for a given domain to the keychain.\n public func save(domain: String, username: String, password: String) throws {\n let kq = KeychainQuery()\n try kq.save(id: self.id, host: domain, user: username, token: password)\n }\n\n /// Prompt for authorization data for a given domain to be saved to the keychain.\n /// This will cause the current terminal to enter a password prompt state where\n /// key strokes are hidden.\n public func credentialPrompt(domain: String) throws -> Authentication {\n let username = try userPrompt(domain: domain)\n let password = try passwordPrompt()\n return BasicAuthentication(username: username, password: password)\n }\n\n /// Prompts the current stdin for a username entry and then returns the value.\n public func userPrompt(domain: String) throws -> String {\n print(\"Provide registry username \\(domain): \", terminator: \"\")\n guard let username = readLine() else {\n throw Self.Error.invalidInput\n }\n return username\n }\n\n /// Prompts the current stdin for a password entry and then returns the value.\n /// This will cause the current stdin (if it is a terminal) to hide keystrokes\n /// by disabling echo.\n public func passwordPrompt() throws -> String {\n print(\"Provide registry password: \", terminator: \"\")\n let console = try Terminal.current\n defer { console.tryReset() }\n try console.disableEcho()\n\n guard let password = readLine() else {\n throw Self.Error.invalidInput\n }\n return password\n }\n}\n\nextension KeychainHelper {\n /// `KeychainHelper` errors.\n public enum Error: Swift.Error {\n case keyNotFound\n case invalidInput\n case queryError(String)\n }\n}\n#endif\n"], ["/containerization/Sources/ContainerizationExtras/CIDRAddress.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Describes an IPv4 CIDR address block.\npublic struct CIDRAddress: CustomStringConvertible, Equatable, Sendable {\n\n /// The base IPv4 address of the CIDR block.\n public let lower: IPv4Address\n\n /// The last IPv4 address of the CIDR block\n public let upper: IPv4Address\n\n /// The IPv4 address component of the CIDR block.\n public let address: IPv4Address\n\n /// The address prefix length for the CIDR block, which determines its size.\n public let prefixLength: PrefixLength\n\n /// Create an CIDR address block from its text representation.\n public init(_ cidr: String) throws {\n let split = cidr.components(separatedBy: \"/\")\n guard split.count == 2 else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n address = try IPv4Address(split[0])\n guard let prefixLength = PrefixLength(split[1]) else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n guard prefixLength >= 0 && prefixLength <= 32 else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n\n self.prefixLength = prefixLength\n lower = address.prefix(prefixLength: prefixLength)\n upper = IPv4Address(fromValue: lower.value + prefixLength.suffixMask32)\n }\n\n /// Create a CIDR address from a member IP and a prefix length.\n public init(_ address: IPv4Address, prefixLength: PrefixLength) throws {\n guard prefixLength >= 0 && prefixLength <= 32 else {\n throw NetworkAddressError.invalidCIDR(cidr: \"\\(address)/\\(prefixLength)\")\n }\n\n self.prefixLength = prefixLength\n self.address = address\n lower = address.prefix(prefixLength: prefixLength)\n upper = IPv4Address(fromValue: lower.value + prefixLength.suffixMask32)\n }\n\n /// Create the smallest CIDR block that includes the lower and upper bounds.\n public init(lower: IPv4Address, upper: IPv4Address) throws {\n guard lower.value <= upper.value else {\n throw NetworkAddressError.invalidAddressRange(lower: lower.description, upper: upper.description)\n }\n\n address = lower\n for prefixLength: PrefixLength in 1...32 {\n // find the first case where a subnet mask would put lower and upper in different CIDR block\n let mask = prefixLength.prefixMask32\n\n if (lower.value & mask) != (upper.value & mask) {\n self.prefixLength = prefixLength - 1\n self.lower = address.prefix(prefixLength: self.prefixLength)\n self.upper = IPv4Address(fromValue: self.lower.value + self.prefixLength.suffixMask32)\n return\n }\n }\n\n // if lower and upper are same, create a /32 block\n self.prefixLength = 32\n self.lower = lower\n self.upper = upper\n }\n\n /// Get the offset of the specified address, relative to the\n /// base address for the CIDR block, returning nil if the block\n /// does not contain the address.\n public func getIndex(_ address: IPv4Address) -> UInt32? {\n guard address.value >= lower.value && address.value <= upper.value else {\n return nil\n }\n\n return address.value - lower.value\n }\n\n /// Return true if the CIDR block contains the specified address.\n public func contains(ipv4: IPv4Address) -> Bool {\n lower.value <= ipv4.value && ipv4.value <= upper.value\n }\n\n /// Return true if the CIDR block contains all addresses of another CIDR block.\n public func contains(cidr: CIDRAddress) -> Bool {\n lower.value <= cidr.lower.value && cidr.upper.value <= upper.value\n }\n\n /// Return true if the CIDR block shares any addresses with another CIDR block.\n public func overlaps(cidr: CIDRAddress) -> Bool {\n (lower.value <= cidr.lower.value && upper.value >= cidr.lower.value)\n || (upper.value >= cidr.upper.value && lower.value <= cidr.upper.value)\n }\n\n /// Retrieve the text representation of the CIDR block.\n public var description: String {\n \"\\(address)/\\(prefixLength)\"\n }\n}\n\nextension CIDRAddress: Codable {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n let text = try container.decode(String.self)\n try self.init(text)\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n try container.encode(self.description)\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Path.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// `Path` provides utilities to look for binaries in the current PATH,\n/// or to return the current PATH.\npublic struct Path {\n /// lookPath looks up an executable's path from $PATH\n public static func lookPath(_ name: String) -> URL? {\n lookup(name, path: getPath())\n }\n\n // getEnv returns the default environment of the process\n // with the default $PATH added for the context of a macOS application bundle\n public static func getEnv() -> [String: String] {\n var env = ProcessInfo.processInfo.environment\n env[\"PATH\"] = getPath()\n return env\n }\n\n private static func lookup(_ name: String, path: String) -> URL? {\n if name.contains(\"/\") {\n if findExec(name) {\n return URL(fileURLWithPath: name)\n }\n return nil\n }\n\n for var lookdir in path.split(separator: \":\") {\n if lookdir.isEmpty {\n lookdir = \".\"\n }\n let file = URL(fileURLWithPath: String(lookdir)).appendingPathComponent(name)\n if findExec(file.path) {\n return file\n }\n }\n return nil\n }\n\n /// getPath returns $PATH for the current process\n private static func getPath() -> String {\n let env = ProcessInfo.processInfo.environment\n return env[\"PATH\"] ?? \"/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin\"\n }\n\n // findPath returns a string containing the 'PATH' environment variable\n private static func findPath(_ env: [String]) -> String? {\n env.first(where: { path in\n let split = path.split(separator: \"=\")\n return split.count == 2 && split[0] == \"PATH\"\n })\n }\n\n // findExec returns true if the provided path is an executable\n private static func findExec(_ path: String) -> Bool {\n let fm = FileManager.default\n return fm.isExecutableFile(atPath: path)\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/AsyncSignalHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Synchronization\n\n/// Async friendly wrapper around `DispatchSourceSignal`. Provides an `AsyncStream`\n/// interface to get notified of received signals.\npublic final class AsyncSignalHandler: Sendable {\n /// An async stream that returns the signal that was caught, if ever.\n public var signals: AsyncStream {\n let (stream, cont) = AsyncStream.makeStream(of: Int32.self)\n self.state.withLock {\n $0.conts.append(cont)\n }\n cont.onTermination = { @Sendable _ in\n self.cancel()\n }\n return stream\n }\n\n /// Cancel every AsyncStream of signals, as well as the underlying\n /// DispatchSignalSource's for each registered signal.\n public func cancel() {\n self.state.withLock {\n if $0.conts.isEmpty {\n return\n }\n\n for cont in $0.conts {\n cont.finish()\n }\n for source in $0.sources {\n source.cancel()\n }\n $0.conts.removeAll()\n $0.sources.removeAll()\n }\n }\n\n struct State: Sendable {\n var conts: [AsyncStream.Continuation] = []\n nonisolated(unsafe) var sources: [any DispatchSourceSignal] = []\n }\n\n // We keep a reference to the continuation object that is created for\n // our AsyncStream and tell our signal handler to yield a value to it\n // returning a value to the consumer\n private func handler(_ sig: Int32) {\n self.state.withLock {\n for cont in $0.conts {\n cont.yield(sig)\n }\n }\n }\n\n private let state: Mutex = .init(State())\n\n /// Create a new `AsyncSignalHandler` for the list of given signals `notify`.\n /// The default signal handlers for these signals are removed and async handlers\n /// added in their place. The async signal handlers that are installed simply\n /// yield to a stream if and when a signal is caught.\n public static func create(notify on: [Int32]) -> AsyncSignalHandler {\n let out = AsyncSignalHandler()\n var sources = [any DispatchSourceSignal]()\n for sig in on {\n signal(sig, SIG_IGN)\n let source = DispatchSource.makeSignalSource(signal: sig)\n source.setEventHandler {\n out.handler(sig)\n }\n source.resume()\n // Retain a reference to our signal sources so that they\n // do not go out of scope.\n sources.append(source)\n }\n out.state.withLock { $0.sources = sources }\n return out\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/NetworkAddress+Allocator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension IPv4Address {\n /// Creates an allocator for IPv4 addresses.\n public static func allocator(lower: UInt32, size: Int) throws -> any AddressAllocator {\n // NOTE: 2^31 - 1 size limit in the very improbable case that we run on 32-bit.\n guard size > 0 && size < Int.max && 0xffff_ffff - lower >= size - 1 else {\n throw AllocatorError.rangeExceeded\n }\n return IndexedAddressAllocator(\n size: size,\n addressToIndex: { address in\n guard address.value >= lower && address.value - lower <= UInt32(size) else {\n return nil\n }\n return Int(address.value - lower)\n },\n indexToAddress: { IPv4Address(fromValue: lower + UInt32($0)) }\n )\n }\n}\n\nextension UInt16 {\n /// Creates an allocator for TCP/UDP ports and other UInt16 values.\n public static func allocator(lower: UInt16, size: Int) throws -> any AddressAllocator {\n guard 0xffff - lower + 1 >= size else {\n throw AllocatorError.rangeExceeded\n }\n\n return IndexedAddressAllocator(\n size: size,\n addressToIndex: { address in\n guard address >= lower && address <= lower + UInt16(size) else {\n return nil\n }\n return Int(address - lower)\n },\n indexToAddress: { lower + UInt16($0) }\n )\n }\n}\n\nextension UInt32 {\n /// Creates an allocator for vsock ports, or any UInt32 values.\n public static func allocator(lower: UInt32, size: Int) throws -> any AddressAllocator {\n guard 0xffff_ffff - lower + 1 >= size else {\n throw AllocatorError.rangeExceeded\n }\n\n return IndexedAddressAllocator(\n size: size,\n addressToIndex: { address in\n guard address >= lower && address <= lower + UInt32(size) else {\n return nil\n }\n return Int(address - lower)\n },\n indexToAddress: { lower + UInt32($0) }\n )\n }\n\n /// Creates a rotating allocator for vsock ports, or any UInt32 values.\n public static func rotatingAllocator(lower: UInt32, size: UInt32) throws -> any AddressAllocator {\n guard 0xffff_ffff - lower + 1 >= size else {\n throw AllocatorError.rangeExceeded\n }\n\n return RotatingAddressAllocator(\n size: size,\n addressToIndex: { address in\n guard address >= lower && address <= lower + UInt32(size) else {\n return nil\n }\n return Int(address - lower)\n },\n indexToAddress: { lower + UInt32($0) }\n )\n }\n}\n\nextension Character {\n private static let deviceLetters = Array(\"abcdefghijklmnopqrstuvwxyz\")\n\n /// Creates an allocator for block device tags, or any character values.\n public static func blockDeviceTagAllocator() -> any AddressAllocator {\n IndexedAddressAllocator(\n size: Self.deviceLetters.count,\n addressToIndex: { address in\n Self.deviceLetters.firstIndex(of: address)\n },\n indexToAddress: { Self.deviceLetters[$0] }\n )\n }\n}\n"], ["/containerization/Sources/SendablePropertyMacros/SendablePropertyMacro.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SwiftCompilerPlugin\nimport SwiftParser\nimport SwiftSyntax\nimport SwiftSyntaxBuilder\nimport SwiftSyntaxMacros\n\n/// A macro that allows to make a property of a supported type thread-safe keeping the `Sendable` conformance of the type.\npublic struct SendablePropertyMacro: PeerMacro {\n private static let allowedTypes: Set = [\n \"Int\", \"UInt\", \"Int16\", \"UInt16\", \"Int32\", \"UInt32\", \"Int64\", \"UInt64\", \"Float\", \"Double\", \"Bool\", \"UnsafeRawPointer\", \"UnsafeMutableRawPointer\", \"UnsafePointer\",\n \"UnsafeMutablePointer\",\n ]\n\n private static func checkPropertyType(in declaration: some DeclSyntaxProtocol) throws {\n guard let varDecl = declaration.as(VariableDeclSyntax.self),\n let binding = varDecl.bindings.first,\n let typeAnnotation = binding.typeAnnotation,\n let id = typeAnnotation.type.as(IdentifierTypeSyntax.self)\n else {\n // Nothing to check.\n return\n }\n\n var typeName = id.name.text\n // Allow optionals of the allowed types.\n if typeName.prefix(9) == \"Optional<\" && typeName.suffix(1) == \">\" {\n typeName = String(typeName.dropFirst(9).dropLast(1))\n }\n // Allow generics of the allowed types.\n if typeName.contains(\"<\") {\n typeName = String(typeName.prefix { $0 != \"<\" })\n }\n\n guard allowedTypes.contains(typeName) else {\n throw SendablePropertyError.notApplicableToType\n }\n }\n\n /// The macro expansion that introduces a `Sendable`-conforming \"peer\" declaration for a thread-safe storage for the value of the given declaration of a variable.\n /// - Parameters:\n /// - node: The given attribute node.\n /// - declaration: The given declaration.\n /// - context: The macro expansion context.\n public static func expansion(\n of node: SwiftSyntax.AttributeSyntax, providingPeersOf declaration: some SwiftSyntax.DeclSyntaxProtocol, in context: some SwiftSyntaxMacros.MacroExpansionContext\n ) throws -> [SwiftSyntax.DeclSyntax] {\n try checkPropertyType(in: declaration)\n return try SendablePropertyMacroUnchecked.expansion(of: node, providingPeersOf: declaration, in: context)\n }\n}\n\nextension SendablePropertyMacro: AccessorMacro {\n /// The macro expansion that adds `Sendable`-conforming accessors to the given declaration of a variable.\n /// - Parameters:\n /// - node: The given attribute node.\n /// - declaration: The given declaration.\n /// - context: The macro expansion context.\n public static func expansion(\n of node: SwiftSyntax.AttributeSyntax, providingAccessorsOf declaration: some SwiftSyntax.DeclSyntaxProtocol, in context: some SwiftSyntaxMacros.MacroExpansionContext\n ) throws -> [SwiftSyntax.AccessorDeclSyntax] {\n try checkPropertyType(in: declaration)\n return try SendablePropertyMacroUnchecked.expansion(of: node, providingAccessorsOf: declaration, in: context)\n }\n}\n"], ["/containerization/Sources/Containerization/Image/Image.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\n\n/// Type representing an OCI container image.\npublic struct Image: Sendable {\n private let contentStore: ContentStore\n /// The description for the image that comprises of its name and a reference to its root descriptor.\n public let description: Description\n\n /// A description of the OCI image.\n public struct Description: Sendable {\n /// The string reference of the image.\n public let reference: String\n /// The descriptor identifying the image.\n public let descriptor: Descriptor\n /// The digest for the image.\n public var digest: String { descriptor.digest }\n /// The media type of the image.\n public var mediaType: String { descriptor.mediaType }\n\n public init(reference: String, descriptor: Descriptor) {\n self.reference = reference\n self.descriptor = descriptor\n }\n }\n\n /// The descriptor for the image.\n public var descriptor: Descriptor { description.descriptor }\n /// The digest of the image.\n public var digest: String { description.digest }\n /// The media type of the image.\n public var mediaType: String { description.mediaType }\n /// The string reference for the image.\n public var reference: String { description.reference }\n\n public init(description: Description, contentStore: ContentStore) {\n self.description = description\n self.contentStore = contentStore\n }\n\n /// Returns the underlying OCI index for the image.\n public func index() async throws -> Index {\n guard let content: Content = try await contentStore.get(digest: digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(digest)\")\n }\n return try content.decode()\n }\n\n /// Returns the manifest for the specified platform.\n public func manifest(for platform: Platform) async throws -> Manifest {\n let index = try await self.index()\n let desc = index.manifests.first { desc in\n desc.platform == platform\n }\n guard let desc else {\n throw ContainerizationError(.unsupported, message: \"Platform \\(platform.description)\")\n }\n guard let content: Content = try await contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(digest)\")\n }\n return try content.decode()\n }\n\n /// Returns the descriptor for the given platform. If it does not exist\n /// will throw a ContainerizationError with the code set to .invalidArgument.\n public func descriptor(for platform: Platform) async throws -> Descriptor {\n let index = try await self.index()\n let desc = index.manifests.first { $0.platform == platform }\n guard let desc else {\n throw ContainerizationError(.invalidArgument, message: \"unsupported platform \\(platform)\")\n }\n return desc\n }\n\n /// Returns the OCI config for the specified platform.\n public func config(for platform: Platform) async throws -> ContainerizationOCI.Image {\n let manifest = try await self.manifest(for: platform)\n let desc = manifest.config\n guard let content: Content = try await contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(digest)\")\n }\n return try content.decode()\n }\n\n /// Returns a list of digests to all the referenced OCI objects.\n public func referencedDigests() async throws -> [String] {\n var referenced: [String] = [self.digest.trimmingDigestPrefix]\n let index = try await self.index()\n for manifest in index.manifests {\n referenced.append(manifest.digest.trimmingDigestPrefix)\n guard let m: Manifest = try? await contentStore.get(digest: manifest.digest) else {\n // If the requested digest does not exist or is not a manifest. Skip.\n // Its safe to skip processing this digest as it wont have any child layers.\n continue\n }\n let descs = m.layers + [m.config]\n referenced.append(contentsOf: descs.map { $0.digest.trimmingDigestPrefix })\n }\n return referenced\n }\n\n /// Returns a reference to the content blob for the image. The specified digest must be referenced by the image in one of its layers.\n public func getContent(digest: String) async throws -> Content {\n guard try await self.referencedDigests().contains(digest.trimmingDigestPrefix) else {\n throw ContainerizationError(.internalError, message: \"Image \\(self.reference) does not reference digest \\(digest)\")\n }\n guard let content: Content = try await contentStore.get(digest: digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(digest)\")\n }\n return content\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/ContentWriter.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Crypto\nimport Foundation\nimport NIOCore\n\n/// Provides a context to write data into a directory.\npublic class ContentWriter {\n private let base: URL\n private let encoder = JSONEncoder()\n\n /// Create a new ContentWriter.\n /// - Parameters:\n /// - base: The URL to write content to. If this is not a directory a\n /// ContainerizationError will be thrown with a code of .internalError.\n public init(for base: URL) throws {\n self.encoder.outputFormatting = [JSONEncoder.OutputFormatting.sortedKeys]\n\n self.base = base\n var isDirectory = ObjCBool(true)\n let exists = FileManager.default.fileExists(atPath: base.path, isDirectory: &isDirectory)\n\n guard exists && isDirectory.boolValue else {\n throw ContainerizationError(.internalError, message: \"Cannot create ContentWriter for path \\(base.absolutePath()). Not a directory\")\n }\n }\n\n /// Writes the data blob to the base URL provided in the constructor.\n /// - Parameters:\n /// - data: The data blob to write to a file under the base path.\n @discardableResult\n public func write(_ data: Data) throws -> (size: Int64, digest: SHA256.Digest) {\n let digest = SHA256.hash(data: data)\n let destination = base.appendingPathComponent(digest.encoded)\n try data.write(to: destination)\n return (Int64(data.count), digest)\n }\n\n /// Reads the data present in the passed in URL and writes it to the base path.\n /// - Parameters:\n /// - url: The URL to read the data from.\n @discardableResult\n public func create(from url: URL) throws -> (size: Int64, digest: SHA256.Digest) {\n let data = try Data(contentsOf: url)\n return try self.write(data)\n }\n\n /// Encodes the passed in type as a JSON blob and writes it to the base path.\n /// - Parameters:\n /// - content: The type to convert to JSON.\n @discardableResult\n public func create(from content: T) throws -> (size: Int64, digest: SHA256.Digest) {\n let data = try self.encoder.encode(content)\n return try self.write(data)\n }\n}\n"], ["/containerization/Sources/SendablePropertyMacros/SendablePropertyMacroUnchecked.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SwiftCompilerPlugin\nimport SwiftParser\nimport SwiftSyntax\nimport SwiftSyntaxBuilder\nimport SwiftSyntaxMacros\n\n/// A macro that allows to make a property of a custom type thread-safe keeping the `Sendable` conformance of the type. This macro can be used with classes and enums. Avoid using it with structs, arrays, and dictionaries.\npublic struct SendablePropertyMacroUnchecked: PeerMacro {\n private static func peerPropertyName(for propertyName: String) -> String {\n \"_\" + propertyName\n }\n\n /// The macro expansion that introduces a `Sendable`-conforming \"peer\" declaration for a thread-safe storage for the value of the given declaration of a variable.\n /// - Parameters:\n /// - node: The given attribute node.\n /// - declaration: The given declaration.\n /// - context: The macro expansion context.\n public static func expansion(\n of node: SwiftSyntax.AttributeSyntax, providingPeersOf declaration: some SwiftSyntax.DeclSyntaxProtocol, in context: some SwiftSyntaxMacros.MacroExpansionContext\n ) throws -> [SwiftSyntax.DeclSyntax] {\n guard let varDecl = declaration.as(VariableDeclSyntax.self),\n let binding = varDecl.bindings.first,\n let pattern = binding.pattern.as(IdentifierPatternSyntax.self)\n else {\n throw SendablePropertyError.onlyApplicableToVar\n }\n\n let propertyName = pattern.identifier.text\n let hasInitializer = binding.initializer != nil\n let initializerValue = binding.initializer?.value.description ?? \"nil\"\n\n var genericTypeAnnotation = \"\"\n if let typeAnnotation = binding.typeAnnotation {\n let typeName = typeAnnotation.type.description.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)\n genericTypeAnnotation = \"<\\(typeName)\\(hasInitializer ? \"\" : \"?\")>\"\n }\n\n let accessLevel = varDecl.modifiers.first(where: { [\"open\", \"public\", \"internal\", \"fileprivate\", \"private\"].contains($0.name.text) })?.name.text ?? \"internal\"\n\n // Create a peer property\n let peerPropertyName = self.peerPropertyName(for: propertyName)\n let peerProperty: DeclSyntax =\n \"\"\"\n \\(raw: accessLevel) let \\(raw: peerPropertyName) = Synchronized\\(raw: genericTypeAnnotation)(\\(raw: initializerValue))\n \"\"\"\n return [peerProperty]\n }\n}\n\nextension SendablePropertyMacroUnchecked: AccessorMacro {\n /// The macro expansion that adds `Sendable`-conforming accessors to the given declaration of a variable.\n /// - Parameters:\n /// - node: The given attribute node.\n /// - declaration: The given declaration.\n /// - context: The macro expansion context.\n public static func expansion(\n of node: SwiftSyntax.AttributeSyntax, providingAccessorsOf declaration: some SwiftSyntax.DeclSyntaxProtocol, in context: some SwiftSyntaxMacros.MacroExpansionContext\n ) throws -> [SwiftSyntax.AccessorDeclSyntax] {\n guard let varDecl = declaration.as(VariableDeclSyntax.self),\n let binding = varDecl.bindings.first,\n let pattern = binding.pattern.as(IdentifierPatternSyntax.self)\n else {\n throw SendablePropertyError.onlyApplicableToVar\n }\n\n let propertyName = pattern.identifier.text\n let hasInitializer = binding.initializer != nil\n\n // Replace the property with an accessor\n let peerPropertyName = Self.peerPropertyName(for: propertyName)\n\n let accessorGetter: AccessorDeclSyntax =\n \"\"\"\n get {\n \\(raw: peerPropertyName).withLock { $0\\(raw: hasInitializer ? \"\" : \"!\") }\n }\n \"\"\"\n let accessorSetter: AccessorDeclSyntax =\n \"\"\"\n set {\n \\(raw: peerPropertyName).withLock { $0 = newValue }\n }\n \"\"\"\n\n return [accessorGetter, accessorSetter]\n }\n}\n"], ["/containerization/Sources/Containerization/VirtualMachineInstance.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// The runtime state of the virtual machine instance.\npublic enum VirtualMachineInstanceState: Sendable {\n case starting\n case running\n case stopped\n case stopping\n case unknown\n}\n\n/// A live instance of a virtual machine.\npublic protocol VirtualMachineInstance: Sendable {\n associatedtype Agent: VirtualMachineAgent\n\n // The state of the virtual machine.\n var state: VirtualMachineInstanceState { get }\n\n var mounts: [AttachedFilesystem] { get }\n /// Dial the Agent. It's up the VirtualMachineInstance to determine\n /// what port the agent is listening on.\n func dialAgent() async throws -> Agent\n /// Dial a vsock port in the guest.\n func dial(_ port: UInt32) async throws -> FileHandle\n /// Listen on a host vsock port.\n func listen(_ port: UInt32) throws -> VsockConnectionStream\n /// Stop listening on a vsock port.\n func stopListen(_ port: UInt32) throws\n /// Start the virtual machine.\n func start() async throws\n /// Stop the virtual machine.\n func stop() async throws\n}\n"], ["/containerization/vminitd/Sources/vmexec/Mount.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Musl\n\nstruct ContainerMount {\n private let mounts: [ContainerizationOCI.Mount]\n private let rootfs: String\n\n init(rootfs: String, mounts: [ContainerizationOCI.Mount]) {\n self.rootfs = rootfs\n self.mounts = mounts\n }\n\n func mountToRootfs() throws {\n for m in self.mounts {\n let osMount = m.toOSMount()\n try osMount.mount(root: self.rootfs)\n }\n }\n\n func configureConsole() throws {\n let ptmx = self.rootfs.standardizingPath.appendingPathComponent(\"/dev/ptmx\")\n\n guard remove(ptmx) == 0 else {\n throw App.Errno(stage: \"remove(ptmx)\")\n }\n guard symlink(\"pts/ptmx\", ptmx) == 0 else {\n throw App.Errno(stage: \"symlink(pts/ptmx)\")\n }\n }\n\n private func mkdirAll(_ name: String, _ perm: Int16) throws {\n try FileManager.default.createDirectory(\n atPath: name,\n withIntermediateDirectories: true,\n attributes: [.posixPermissions: perm]\n )\n }\n}\n\nextension ContainerizationOCI.Mount {\n func toOSMount() -> ContainerizationOS.Mount {\n ContainerizationOS.Mount(\n type: self.type,\n source: self.source,\n target: self.destination,\n options: self.options\n )\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/AsyncLock.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// `AsyncLock` provides a familiar locking API, with the main benefit being that it\n/// is safe to call async methods while holding the lock. This is primarily used in spots\n/// where an actor makes sense, but we may need to ensure we don't fall victim to actor\n/// reentrancy issues.\npublic actor AsyncLock {\n private var busy = false\n private var queue: ArraySlice> = []\n\n public struct Context: Sendable {\n fileprivate init() {}\n }\n\n public init() {}\n\n /// withLock provides a scoped locking API to run a function while holding the lock.\n public func withLock(_ body: @Sendable @escaping (Context) async throws -> T) async rethrows -> T {\n while self.busy {\n await withCheckedContinuation { cc in\n self.queue.append(cc)\n }\n }\n\n self.busy = true\n\n defer {\n self.busy = false\n if let next = self.queue.popFirst() {\n next.resume(returning: ())\n } else {\n self.queue = []\n }\n }\n\n let context = Context()\n return try await body(context)\n }\n}\n"], ["/containerization/Sources/Containerization/Image/InitImage.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\n/// Data representing the image to use as the root filesystem for a virtual machine.\n/// Typically this image would contain the guest agent used to facilitate container\n/// workloads, as well as any extras that may be useful to have in the guest.\npublic struct InitImage: Sendable {\n public var name: String { image.reference }\n\n let image: Image\n\n public init(image: Image) {\n self.image = image\n }\n}\n\nextension InitImage {\n /// Unpack the initial filesystem for the desired platform at a given path.\n public func initBlock(at: URL, for platform: SystemPlatform) async throws -> Mount {\n let unpacker = EXT4Unpacker(blockSizeInBytes: 512.mib())\n var fs = try await unpacker.unpack(self.image, for: platform.ociPlatform(), at: at)\n fs.options = [\"ro\"]\n return fs\n }\n\n /// Create a new InitImage with the reference as the name.\n /// The `rootfs` parameter must be a tar.gz file whose contents make up the filesystem for the image.\n public static func create(\n reference: String, rootfs: URL, platform: Platform,\n labels: [String: String] = [:], imageStore: ImageStore, contentStore: ContentStore\n ) async throws -> InitImage {\n\n let indexDescriptorStore = AsyncStore()\n try await contentStore.ingest { dir in\n let writer = try ContentWriter(for: dir)\n var result = try writer.create(from: rootfs)\n let layerDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.imageLayerGzip, digest: result.digest.digestString, size: result.size)\n\n // TODO: compute and fill in the correct diffID for the above layer\n // We currently put in the sha of the fully compressed layer, this needs to be replaced with\n // the sha of the uncompressed layer.\n let rootfsConfig = ContainerizationOCI.Rootfs(type: \"layers\", diffIDs: [result.digest.digestString])\n let runtimeConfig = ContainerizationOCI.ImageConfig(labels: labels)\n let imageConfig = ContainerizationOCI.Image(architecture: platform.architecture, os: platform.os, config: runtimeConfig, rootfs: rootfsConfig)\n result = try writer.create(from: imageConfig)\n let configDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.imageConfig, digest: result.digest.digestString, size: result.size)\n\n let manifest = Manifest(config: configDescriptor, layers: [layerDescriptor])\n result = try writer.create(from: manifest)\n let manifestDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.imageManifest, digest: result.digest.digestString, size: result.size, platform: platform)\n\n let index = ContainerizationOCI.Index(manifests: [manifestDescriptor])\n result = try writer.create(from: index)\n\n let indexDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.index, digest: result.digest.digestString, size: result.size)\n await indexDescriptorStore.set(indexDescriptor)\n\n }\n\n guard let indexDescriptor = await indexDescriptorStore.get() else {\n throw ContainerizationError(.notFound, message: \"image for \\(reference) not found\")\n }\n\n let description = Image.Description(reference: reference, descriptor: indexDescriptor)\n let image = try await imageStore.create(description: description)\n return InitImage(image: image)\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\n\n/**\n ```\n# EXT4 Filesystem Layout\n\n The EXT4 filesystem divides the disk into an upfront metadata section followed by several logical groups known as block groups. The\n metadata section looks like this:\n\n +--------------------------+\n | Boot Sector (1024) |\n +--------------------------+\n | Superblock (1024) |\n +--------------------------+\n | Empty (2048) |\n +--------------------------+\n | |\n | [Block Group Descriptors]|\n | |\n | - Free/used block bitmap |\n | - Free/used inode bitmap |\n | - Inode table pointer |\n | - Other metadata |\n | |\n +--------------------------+\n\n ## Block Groups\n\n Each block group optionally stores a copy of the superblock and group descriptor table for disaster recovery.\n The rest of the block group comprises of data blocks. The size of each block group is dynamically decided\n while formatting, based on total amount of space available on the disk.\n\n +--------------------------+\n | Block Group 0 |\n | +------------------+ |\n | | Super Block | |\n | +------------------+ |\n | | Group Desc. | |\n | +------------------+ |\n | | Data Blocks | |\n | | | |\n | +------------------+ |\n +--------------------------+\n | Block Group 1 |\n | +------------------+ |\n | | Super Block | |\n | +------------------+ |\n | | Group Desc. | |\n | +------------------+ |\n | | Data Blocks | |\n | | | |\n | +------------------+ |\n +--------------------------+\n | ... |\n +--------------------------+\n | Block Group N |\n | +------------------+ |\n | | Super Block | |\n | +------------------+ |\n | | Group Desc. | |\n | +------------------+ |\n | | Data Blocks | |\n | | | |\n | +------------------+ |\n +--------------------------+\n\n The descriptor for each block group contain the following information:\n\n - Block Bitmap\n - Inode Bitmap\n - Pointer to Inode Table\n - other metadata such as used block count, num. dirs etc.\n\n ### Block Bitmap\n\n A sequence of bits, where each bit represents a block in the block group.\n\n 1: In use block\n 0: Free block\n\n +---------------+---------------+\n | Block |\n | Bitmap |\n +---------------+---------------+\n | 1 0 1 0 1 1 0 0 |\n +---------------+---------------+\n | | | | | | | |\n | | | | | | | |\n v v v v v v v v\n +---+---+---+---+---+---+---+---+\n | B | | B | | B | B | | |\n +---+---+---+---+---+---+---+---+\n\n Whenever a file is created, free data blocks are identified by using this table.\n When it is deleted, the corresponding data blocks are marked as free.\n\n ### Inode Bitmap\n\n A sequence of bits, where each bit represents a inode in the block group. Since\n inodes per group is a fixed number, this bitmap is made to be of sufficient length\n to accommodate that many inodes\n\n 1: In use inode\n 0: Free inode\n\n +---------------+---------------+\n | Inode |\n | Bitmap |\n +---------------+---------------+\n | 1 0 1 0 1 1 0 0 |\n +---------------+---------------+\n | | | | | | | |\n | | | | | | | |\n v v v v v v v v\n +---+---+---+---+---+---+---+---+\n | I | | I | | I | I | | |\n +---+---+---+---+---+---+---+---+\n\n ## Inode table\n\n Inode table provides a mapping from Inode -> Data blocks. In this implementation, inode size is set to 256 bytes.\n Inode table uses extents to efficiently describe the mapping.\n\n +-----------------------+\n | Inode Table |\n +-----------------------+\n | Inode | Metadata |\n +-------+---------------+\n | 1 | permissions |\n | | size |\n | | user ID |\n | | group ID |\n | | timestamps |\n | | block |\n | | blocks count |\n +-------+---------------+\n | 2 | ... |\n +-------+---------------+\n | ... | ... |\n +-------+---------------+\n\n The length of `block` field in the inode table is 60 bytes. This field contains an extent tree\n that holds information about ranges of blocks used by the file. For smaller files, the entire extent\n tree can be stored within this field.\n\n +-----------------------+\n | Inode |\n +-----------------------+\n | Metadata |\n +-----------------------+\n | Extent Tree |\n | +-------------------+ |\n | | Extent Leaf Node | |\n | +-------------------+ |\n | | - Start Block | |\n | | - Block Count | |\n | | - ... | |\n | +-------------------+ |\n +-----------------------+\n\n For larger files which span across multiple non-contiguous blocks, extent tree's root points to extent\n blocks, which in-turn point to the blocks used by the file\n\n +-----------------------+\n | Extent Tree |\n | +-------------------+ |\n | | Extent Root | |\n | +-------------------+ |\n | | - Pointers to | |\n | | Extent Blocks | |\n | +-------------------+ |\n +-----------------------+\n |\n v\n +-----------------------+\n | Extent Block |\n +-----------------------+\n | +-------------------+ |\n | | Extent Leaf Node | |\n | +-------------------+ |\n | | - Start Block | |\n | | - Block Count | |\n | | - ... | |\n | +-------------------+ |\n | +-------------------+ |\n | | Extent Leaf Node | |\n | +-------------------+ |\n | | - Start Block | |\n | | - Block Count | |\n | | - ... | |\n | +-------------------+ |\n +-----------------------+\n\n ## Directory entries\n\n The data blocks for directory inodes point to a list of directory entrees. Each entry\n consists of only a name and inode number. The name and inode number correspond to the\n name and inode number of the children of the directory\n\n +-------------------------+\n | Directory Entry |\n +-------------------------+\n | inode | rec_len | name |\n +-------------------------+\n | 2 | 1 | \".\" |\n +-------------------------+\n | Directory Entry |\n +-------------------------+\n | inode | rec_len | name |\n +-------------------------+\n | 1 | 2 | \"..\" |\n +-------------------------+\n | Directory Entry |\n +-------------------------+\n | inode | rec_len | name |\n +-------------------------+\n | 11 | 10 | lost& |\n | | | found |\n +-------------------------+\n\nMore details can be found here https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout\n\n```\n*/\n\n/// A type for interacting with ext4 file systems.\n///\n/// The `Ext4` class provides functionality to read the superblock of an existing ext4 block device\n/// and format a new block device with the ext4 file system.\n///\n/// Usage:\n/// - To read the superblock of an existing ext4 block device, create an instance of `Ext4` with the\n/// path to the block device\n/// - To format a new block device with ext4, create an instance of `Ext4.Formatter` with the path to the block\n/// device and call the `close()` method.\n///\n/// Example 1: Read an existing block device\n/// ```swift\n/// let blockDevice = URL(filePath: \"/dev/sdb\")\n/// // succeeds if a valid ext4 fs is found at path\n/// let ext4 = try Ext4(blockDevice: blockDevice)\n/// print(\"Block size: \\(ext4.blockSize)\")\n/// print(\"Total size: \\(ext4.size)\")\n///\n/// // Reading the superblock\n/// let superblock = ext4.superblock\n/// print(\"Superblock information:\")\n/// print(\"Total blocks: \\(superblock.blocksCountLow)\")\n/// ```\n///\n/// Example 2: Format a new block device (Refer [`EXT4.Formatter`](x-source-tag://EXT4.Formatter) for more info)\n/// ```swift\n/// let devicePath = URL(filePath: \"/dev/sdc\")\n/// let formatter = try EXT4.Formatter(devicePath, blockSize: 4096)\n/// try formatter.close()\n/// ```\npublic enum EXT4 {\n public static let SuperBlockMagic: UInt16 = 0xef53\n\n static let ExtentHeaderMagic: UInt16 = 0xf30a\n static let XAttrHeaderMagic: UInt32 = 0xea02_0000\n\n static let DefectiveBlockInode: InodeNumber = 1\n static let RootInode: InodeNumber = 2\n static let FirstInode: InodeNumber = 11\n static let LostAndFoundInode: InodeNumber = 11\n\n static let InodeActualSize: UInt32 = 160 // 160 bytes used by metadata\n static let InodeExtraSize: UInt32 = 96 // 96 bytes for inline xattrs\n static let InodeSize: UInt32 = UInt32(MemoryLayout.size) // 256 bytes. This is the max size of an inode\n static let XattrInodeHeaderSize: UInt32 = 4\n static let XattrBlockHeaderSize: UInt32 = 32\n static let ExtraIsize: UInt16 = UInt16(InodeActualSize) - 128\n\n static let MaxLinks: UInt32 = 65000\n static let MaxBlocksPerExtent: UInt32 = 0x8000\n static let MaxFileSize: UInt64 = 128.gib()\n static let SuperBlockOffset: UInt64 = 1024\n}\n\nextension EXT4 {\n // `EXT4` errors.\n public enum Error: Swift.Error, CustomStringConvertible, Sendable, Equatable {\n case notFound(_ path: String)\n case couldNotReadSuperBlock(_ path: String, _ offset: UInt64, _ size: Int)\n case invalidSuperBlock\n case deepExtentsUnimplemented\n case invalidExtents\n case invalidXattrEntry\n case couldNotReadBlock(_ block: UInt32)\n case invalidPathEncoding(_ path: String)\n case couldNotReadInode(_ inode: UInt32)\n case couldNotReadGroup(_ group: UInt32)\n public var description: String {\n switch self {\n case .notFound(let path):\n return \"file at path \\(path) not found\"\n case .couldNotReadSuperBlock(let path, let offset, let size):\n return \"could not read \\(size) bytes of superblock from \\(path) at offset \\(offset)\"\n case .invalidSuperBlock:\n return \"not a valid EXT4 superblock\"\n case .deepExtentsUnimplemented:\n return \"deep extents are not supported\"\n case .invalidExtents:\n return \"extents invalid or corrupted\"\n case .invalidXattrEntry:\n return \"invalid extended attribute entry\"\n case .couldNotReadBlock(let block):\n return \"could not read block \\(block)\"\n case .invalidPathEncoding(let path):\n return \"path encoding for '\\(path)' is invalid, must be ascii or utf8\"\n case .couldNotReadInode(let inode):\n return \"could not read inode \\(inode)\"\n case .couldNotReadGroup(let group):\n return \"could not read group descriptor \\(group)\"\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/FilePath+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\nextension FilePath {\n public static let Separator: String = \"/\"\n\n public var bytes: [UInt8] {\n self.withCString { cstr in\n var ptr = cstr\n var rawBytes: [UInt8] = []\n while UInt(bitPattern: ptr) != 0 {\n if ptr.pointee == 0x00 { break }\n rawBytes.append(UInt8(bitPattern: ptr.pointee))\n ptr = ptr.successor()\n }\n return rawBytes\n }\n }\n\n public var base: String {\n self.lastComponent?.string ?? \"/\"\n }\n\n public var dir: FilePath {\n self.removingLastComponent()\n }\n\n public var url: URL {\n URL(fileURLWithPath: self.string)\n }\n\n public var items: [String] {\n self.components.map { $0.string }\n }\n\n public init(_ url: URL) {\n self.init(url.path(percentEncoded: false))\n }\n\n public init?(_ data: Data) {\n let cstr: String? = data.withUnsafeBytes { (rbp: UnsafeRawBufferPointer) in\n guard let baseAddress = rbp.baseAddress else {\n return nil\n }\n\n let cString = baseAddress.bindMemory(to: CChar.self, capacity: data.count)\n return String(cString: cString)\n }\n\n guard let cstr else {\n return nil\n }\n self.init(cstr)\n }\n\n public func join(_ path: FilePath) -> FilePath {\n self.pushing(path)\n }\n\n public func join(_ path: String) -> FilePath {\n self.join(FilePath(path))\n }\n\n public func split() -> (dir: FilePath, base: String) {\n (self.dir, self.base)\n }\n\n public func clean() -> FilePath {\n self.lexicallyNormalized()\n }\n\n public static func rel(_ basepath: String, _ targpath: String) -> FilePath {\n let base = FilePath(basepath)\n let targ = FilePath(targpath)\n\n if base == targ {\n return \".\"\n }\n\n let baseComponents = base.items\n let targComponents = targ.items\n\n var commonPrefix = 0\n while commonPrefix < min(baseComponents.count, targComponents.count)\n && baseComponents[commonPrefix] == targComponents[commonPrefix]\n {\n commonPrefix += 1\n }\n\n let upCount = baseComponents.count - commonPrefix\n let relComponents = Array(repeating: \"..\", count: upCount) + targComponents[commonPrefix...]\n\n return FilePath(relComponents.joined(separator: Self.Separator))\n }\n}\n\nextension FileHandle {\n public convenience init?(forWritingTo path: FilePath) {\n self.init(forWritingAtPath: path.description)\n }\n\n public convenience init?(forReadingAtPath path: FilePath) {\n self.init(forReadingAtPath: path.description)\n }\n\n public convenience init?(forReadingFrom path: FilePath) {\n self.init(forReadingAtPath: path.description)\n }\n}\n"], ["/containerization/Sources/cctl/cctl.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationOCI\nimport Foundation\nimport Logging\n\nlet log = {\n LoggingSystem.bootstrap(StreamLogHandler.standardError)\n var log = Logger(label: \"com.apple.containerization\")\n log.logLevel = .debug\n return log\n}()\n\n@main\nstruct Application: AsyncParsableCommand {\n static let keychainID = \"com.apple.containerization\"\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.containerization\")\n }()\n\n private static let _contentStore: ContentStore = {\n try! LocalContentStore(path: appRoot.appendingPathComponent(\"content\"))\n }()\n\n private static let _imageStore: ImageStore = {\n try! ImageStore(\n path: appRoot,\n contentStore: contentStore\n )\n }()\n\n static var imageStore: ImageStore {\n _imageStore\n }\n\n static var contentStore: ContentStore {\n _contentStore\n }\n\n static let configuration = CommandConfiguration(\n commandName: \"cctl\",\n abstract: \"Utility CLI for Containerization\",\n version: \"2.0.0\",\n subcommands: [\n Images.self,\n Login.self,\n Rootfs.self,\n Run.self,\n ]\n )\n}\n\nextension String {\n var absoluteURL: URL {\n URL(fileURLWithPath: self).absoluteURL\n }\n}\n\nextension String: Swift.Error {\n\n}\n"], ["/containerization/Sources/ContainerizationArchive/FileArchiveWriterDelegate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\ninternal final class FileArchiveWriterDelegate {\n public let path: FilePath\n private var fd: FileDescriptor!\n\n public init(path: FilePath) {\n self.path = path\n }\n\n public convenience init(url: URL) {\n self.init(path: FilePath(url.path))\n }\n\n public func open(archive: ArchiveWriter) throws {\n self.fd = try FileDescriptor.open(\n self.path, .writeOnly, options: [.create, .append], permissions: [.groupRead, .otherRead, .ownerReadWrite])\n }\n\n public func write(archive: ArchiveWriter, buffer: UnsafeRawBufferPointer) throws -> Int {\n try fd.write(buffer)\n }\n\n public func close(archive: ArchiveWriter) throws {\n try self.fd.close()\n }\n\n public func free(archive: ArchiveWriter) {\n self.fd = nil\n }\n\n deinit {\n if let fd = self.fd {\n try? fd.close()\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Pipe+Close.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension Pipe {\n /// Close both sides of the pipe.\n public func close() throws {\n var err: Swift.Error?\n do {\n try self.fileHandleForReading.close()\n } catch {\n err = error\n }\n try self.fileHandleForWriting.close()\n if let err {\n throw err\n }\n }\n\n /// Ensure that both sides of the pipe are set with O_CLOEXEC.\n public func setCloexec() throws {\n if fcntl(self.fileHandleForWriting.fileDescriptor, F_SETFD, FD_CLOEXEC) == -1 {\n throw POSIXError(.init(rawValue: errno)!)\n }\n if fcntl(self.fileHandleForReading.fileDescriptor, F_SETFD, FD_CLOEXEC) == -1 {\n throw POSIXError(.init(rawValue: errno)!)\n }\n }\n}\n"], ["/containerization/Sources/Containerization/NATNetworkInterface.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\n\nimport vmnet\nimport Virtualization\nimport ContainerizationError\nimport Foundation\nimport Synchronization\n\n/// An interface that uses NAT to provide an IP address for a given\n/// container/virtual machine.\n@available(macOS 26, *)\npublic final class NATNetworkInterface: Interface, Sendable {\n public var address: String {\n get {\n state.withLock { $0.address }\n }\n set {\n state.withLock { $0.address = newValue }\n }\n\n }\n\n public var gateway: String? {\n get {\n state.withLock { $0.gateway }\n }\n set {\n state.withLock { $0.gateway = newValue }\n }\n }\n\n @available(macOS 26, *)\n public var reference: vmnet_network_ref {\n state.withLock { $0.reference }\n }\n\n public var macAddress: String? {\n get {\n state.withLock { $0.macAddress }\n }\n set {\n state.withLock { $0.macAddress = newValue }\n }\n }\n\n private struct State {\n var address: String\n var gateway: String?\n var reference: vmnet_network_ref!\n var macAddress: String?\n }\n\n private let state: Mutex\n\n @available(macOS 26, *)\n public init(\n address: String,\n gateway: String?,\n reference: sending vmnet_network_ref,\n macAddress: String? = nil\n ) {\n let state = State(\n address: address,\n gateway: gateway,\n reference: reference,\n macAddress: macAddress\n )\n self.state = Mutex(state)\n }\n\n @available(macOS, obsoleted: 26, message: \"Use init(address:gateway:reference:macAddress:) instead\")\n public init(\n address: String,\n gateway: String?,\n macAddress: String? = nil\n ) {\n let state = State(\n address: address,\n gateway: gateway,\n reference: nil,\n macAddress: macAddress\n )\n self.state = Mutex(state)\n }\n}\n\n@available(macOS 26, *)\nextension NATNetworkInterface: VZInterface {\n public func device() throws -> VZVirtioNetworkDeviceConfiguration {\n let config = VZVirtioNetworkDeviceConfiguration()\n if let macAddress = self.macAddress {\n guard let mac = VZMACAddress(string: macAddress) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid mac address \\(macAddress)\")\n }\n config.macAddress = mac\n }\n\n config.attachment = VZVmnetNetworkDeviceAttachment(network: self.reference)\n return config\n }\n}\n\n#endif\n"], ["/containerization/Sources/ContainerizationOCI/Client/RegistryClient+Error.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport Foundation\nimport NIOHTTP1\n\nextension RegistryClient {\n /// `RegistryClient` errors.\n public enum Error: Swift.Error, CustomStringConvertible {\n case invalidStatus(url: String, HTTPResponseStatus, reason: String? = nil)\n\n /// Description of the errors.\n public var description: String {\n switch self {\n case .invalidStatus(let u, let response, let reason):\n return \"HTTP request to \\(u) failed with response: \\(response.description). Reason: \\(reason ?? \"Unknown\")\"\n }\n }\n }\n\n /// The container registry typically returns actionable failure reasons in the response body\n /// of the failing HTTP Request. This type models the structure of the error message.\n /// Reference: https://distribution.github.io/distribution/spec/api/#errors\n internal struct ErrorResponse: Codable {\n let errors: [RemoteError]\n\n internal struct RemoteError: Codable {\n let code: String\n let message: String\n let detail: String?\n }\n\n internal static func fromResponseBody(_ body: HTTPClientResponse.Body) async -> ErrorResponse? {\n guard var buffer = try? await body.collect(upTo: Int(1.mib())) else {\n return nil\n }\n guard let bytes = buffer.readBytes(length: buffer.readableBytes) else {\n return nil\n }\n let data = Data(bytes)\n guard let jsonError = try? JSONDecoder().decode(ErrorResponse.self, from: data) else {\n return nil\n }\n return jsonError\n }\n\n public var jsonString: String {\n let data = try? JSONEncoder().encode(self)\n guard let data else {\n return \"{}\"\n }\n return String(data: data, encoding: .utf8) ?? \"{}\"\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Keychain/KeychainQuery.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\n\n/// Holds the result of a query to the keychain.\npublic struct KeychainQueryResult {\n public var account: String\n public var data: String\n public var modifiedDate: Date\n public var createdDate: Date\n}\n\n/// Type that facilitates interacting with the macOS keychain.\npublic struct KeychainQuery {\n public init() {}\n\n /// Save a value to the keychain.\n public func save(id: String, host: String, user: String, token: String) throws {\n if try exists(id: id, host: host) {\n try delete(id: id, host: host)\n }\n\n guard let tokenEncoded = token.data(using: String.Encoding.utf8) else {\n throw Self.Error.invalidTokenConversion\n }\n let query: [String: Any] = [\n kSecClass as String: kSecClassInternetPassword,\n kSecAttrSecurityDomain as String: id,\n kSecAttrServer as String: host,\n kSecAttrAccount as String: user,\n kSecValueData as String: tokenEncoded,\n kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock,\n kSecAttrSynchronizable as String: false,\n ]\n let status = SecItemAdd(query as CFDictionary, nil)\n guard status == errSecSuccess else { throw Self.Error.unhandledError(status: status) }\n }\n\n /// Delete a value from the keychain.\n public func delete(id: String, host: String) throws {\n let query: [String: Any] = [\n kSecClass as String: kSecClassInternetPassword,\n kSecAttrSecurityDomain as String: id,\n kSecAttrServer as String: host,\n kSecMatchLimit as String: kSecMatchLimitOne,\n ]\n let status = SecItemDelete(query as CFDictionary)\n guard status == errSecSuccess || status == errSecItemNotFound else {\n throw Self.Error.unhandledError(status: status)\n }\n }\n\n /// Retrieve a value from the keychain.\n public func get(id: String, host: String) throws -> KeychainQueryResult? {\n let query: [String: Any] = [\n kSecClass as String: kSecClassInternetPassword,\n kSecAttrSecurityDomain as String: id,\n kSecAttrServer as String: host,\n kSecReturnAttributes as String: true,\n kSecMatchLimit as String: kSecMatchLimitOne,\n kSecReturnData as String: true,\n ]\n var item: CFTypeRef?\n let status = SecItemCopyMatching(query as CFDictionary, &item)\n let exists = try isQuerySuccessful(status)\n if !exists {\n return nil\n }\n\n guard let fetched = item as? [String: Any] else {\n throw Self.Error.unexpectedDataFetched\n }\n guard let data = fetched[kSecValueData as String] as? Data else {\n throw Self.Error.keyNotPresent(key: kSecValueData as String)\n }\n guard let decodedData = String(data: data, encoding: String.Encoding.utf8) else {\n throw Self.Error.unexpectedDataFetched\n }\n guard let account = fetched[kSecAttrAccount as String] as? String else {\n throw Self.Error.keyNotPresent(key: kSecAttrAccount as String)\n }\n guard let modifiedDate = fetched[kSecAttrModificationDate as String] as? Date else {\n throw Self.Error.keyNotPresent(key: kSecAttrModificationDate as String)\n }\n guard let createdDate = fetched[kSecAttrCreationDate as String] as? Date else {\n throw Self.Error.keyNotPresent(key: kSecAttrCreationDate as String)\n }\n return KeychainQueryResult(\n account: account,\n data: decodedData,\n modifiedDate: modifiedDate,\n createdDate: createdDate\n )\n }\n\n private func isQuerySuccessful(_ status: Int32) throws -> Bool {\n guard status != errSecItemNotFound else {\n return false\n }\n guard status == errSecSuccess else {\n throw Self.Error.unhandledError(status: status)\n }\n return true\n }\n\n /// Check if a value exists in the keychain.\n public func exists(id: String, host: String) throws -> Bool {\n let query: [String: Any] = [\n kSecClass as String: kSecClassInternetPassword,\n kSecAttrSecurityDomain as String: id,\n kSecAttrServer as String: host,\n kSecReturnAttributes as String: true,\n kSecMatchLimit as String: kSecMatchLimitOne,\n kSecReturnData as String: false,\n ]\n\n let status = SecItemCopyMatching(query as CFDictionary, nil)\n return try isQuerySuccessful(status)\n }\n}\n\nextension KeychainQuery {\n public enum Error: Swift.Error {\n case unhandledError(status: Int32)\n case unexpectedDataFetched\n case keyNotPresent(key: String)\n case invalidTokenConversion\n }\n}\n#endif\n"], ["/containerization/Sources/ContainerizationNetlink/NetlinkSocket.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A protocol for interacting with a netlink socket.\npublic protocol NetlinkSocket {\n var pid: UInt32 { get }\n func send(buf: UnsafeRawPointer!, len: Int, flags: Int32) throws -> Int\n func recv(buf: UnsafeMutableRawPointer!, len: Int, flags: Int32) throws -> Int\n}\n\n/// A netlink socket provider.\npublic typealias NetlinkSocketProvider = () throws -> any NetlinkSocket\n\n/// Errors thrown when interacting with a netlink socket.\npublic enum NetlinkSocketError: Swift.Error, CustomStringConvertible, Equatable {\n case socketFailure(rc: Int32)\n case bindFailure(rc: Int32)\n case sendFailure(rc: Int32)\n case recvFailure(rc: Int32)\n case notImplemented\n\n /// The description of the errors.\n public var description: String {\n switch self {\n case .socketFailure(let rc):\n return \"could not create netlink socket, rc = \\(rc)\"\n case .bindFailure(let rc):\n return \"could not bind netlink socket, rc = \\(rc)\"\n case .sendFailure(let rc):\n return \"could not send netlink packet, rc = \\(rc)\"\n case .recvFailure(let rc):\n return \"could not receive netlink packet, rc = \\(rc)\"\n case .notImplemented:\n return \"socket function not implemented for platform\"\n }\n }\n}\n\n#if canImport(Musl)\nimport Musl\nlet osSocket = Musl.socket\nlet osBind = Musl.bind\nlet osSend = Musl.send\nlet osRecv = Musl.recv\n\n/// A default implementation of `NetlinkSocket`.\npublic class DefaultNetlinkSocket: NetlinkSocket {\n private let sockfd: Int32\n\n /// The process identifier of the process creating this socket.\n public let pid: UInt32\n\n /// Creates a new instance.\n public init() throws {\n pid = UInt32(getpid())\n sockfd = osSocket(Int32(AddressFamily.AF_NETLINK), SocketType.SOCK_RAW, NetlinkProtocol.NETLINK_ROUTE)\n guard sockfd >= 0 else {\n throw NetlinkSocketError.socketFailure(rc: errno)\n }\n\n let addr = SockaddrNetlink(family: AddressFamily.AF_NETLINK, pid: pid)\n var buffer = [UInt8](repeating: 0, count: SockaddrNetlink.size)\n _ = try addr.appendBuffer(&buffer, offset: 0)\n guard let ptr = buffer.bind(as: sockaddr.self, size: buffer.count) else {\n throw NetlinkSocketError.bindFailure(rc: 0)\n }\n guard osBind(sockfd, ptr, UInt32(buffer.count)) >= 0 else {\n throw NetlinkSocketError.bindFailure(rc: errno)\n }\n }\n\n deinit {\n close(sockfd)\n }\n\n /// Sends a request to a netlink socket.\n /// Returns the number of bytes sent.\n /// - Parameters:\n /// - buf: The buffer to send.\n /// - len: The length of the buffer to send.\n /// - flags: The send flags.\n public func send(buf: UnsafeRawPointer!, len: Int, flags: Int32) throws -> Int {\n let count = osSend(sockfd, buf, len, flags)\n guard count >= 0 else {\n throw NetlinkSocketError.sendFailure(rc: errno)\n }\n\n return count\n }\n\n /// Receives a response from a netlink socket.\n /// Returns the number of bytes received.\n /// - Parameters:\n /// - buf: The buffer to receive into.\n /// - len: The maximum number of bytes to receive.\n /// - flags: The receive flags.\n public func recv(buf: UnsafeMutableRawPointer!, len: Int, flags: Int32) throws -> Int {\n let count = osRecv(sockfd, buf, len, flags)\n guard count >= 0 else {\n throw NetlinkSocketError.recvFailure(rc: errno)\n }\n\n return count\n }\n}\n#else\npublic class DefaultNetlinkSocket: NetlinkSocket {\n public var pid: UInt32 { 0 }\n\n public init() throws {}\n\n public func send(buf: UnsafeRawPointer!, len: Int, flags: Int32) throws -> Int {\n throw NetlinkSocketError.notImplemented\n }\n\n public func recv(buf: UnsafeMutableRawPointer!, len: Int, flags: Int32) throws -> Int {\n throw NetlinkSocketError.notImplemented\n }\n}\n#endif\n"], ["/containerization/Sources/ContainerizationOS/URL+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// The `resolvingSymlinksInPath` method of the `URL` struct does not resolve the symlinks\n/// for directories under `/private` which include`tmp`, `var` and `etc`\n/// hence adding a method to build up on the existing `resolvingSymlinksInPath` that prepends `/private` to those paths\nextension URL {\n /// returns the unescaped absolutePath of a URL joined by separator\n func absolutePath(_ separator: String = \"/\") -> String {\n self.pathComponents\n .joined(separator: separator)\n .dropFirst(\"/\".count)\n .description\n }\n\n public func resolvingSymlinksInPathWithPrivate() -> URL {\n let url = self.resolvingSymlinksInPath()\n #if os(macOS)\n let parts = url.pathComponents\n if parts.count > 1 {\n if (parts.first == \"/\") && [\"tmp\", \"var\", \"etc\"].contains(parts[1]) {\n if let resolved = NSURL.fileURL(withPathComponents: [\"/\", \"private\"] + parts[1...]) {\n return resolved\n }\n }\n }\n #endif\n return url\n }\n\n public var isDirectory: Bool {\n (try? resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true\n }\n\n public var isSymlink: Bool {\n (try? resourceValues(forKeys: [.isSymbolicLinkKey]))?.isSymbolicLink == true\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/ArchiveError.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CArchive\nimport Foundation\n\n/// An enumeration of the errors that can be thrown while interacting with an archive.\npublic enum ArchiveError: Error, CustomStringConvertible {\n case unableToCreateArchive\n case noUnderlyingArchive\n case noArchiveInCallback\n case noDelegateConfigured\n case delegateFreedBeforeCallback\n case unableToSetFormat(CInt, Format)\n case unableToAddFilter(CInt, Filter)\n case unableToWriteEntryHeader(CInt)\n case unableToWriteData(CLong)\n case unableToCloseArchive(CInt)\n case unableToOpenArchive(CInt)\n case unableToSetOption(CInt)\n case failedToSetLocale(locales: [String])\n case failedToGetProperty(String, URLResourceKey)\n case failedToDetectFilter\n case failedToDetectFormat\n case failedToExtractArchive(String)\n\n /// Description of the error\n public var description: String {\n switch self {\n case .unableToCreateArchive:\n return \"Unable to create an archive.\"\n case .noUnderlyingArchive:\n return \"No underlying archive was provided.\"\n case .noArchiveInCallback:\n return \"No archive was provided in the callback.\"\n case .noDelegateConfigured:\n return \"No delegate was configured.\"\n case .delegateFreedBeforeCallback:\n return \"The delegate was freed before the callback was invoked.\"\n case .unableToSetFormat(let code, let name):\n return \"Unable to set the archive format \\(name), code \\(code)\"\n case .unableToAddFilter(let code, let name):\n return \"Unable to set the archive filter \\(name), code \\(code)\"\n case .unableToWriteEntryHeader(let code):\n return \"Unable to write the entry header to the archive. Error code \\(code)\"\n case .unableToWriteData(let code):\n return \"Unable to write data to the archive. Error code \\(code)\"\n case .unableToCloseArchive(let code):\n return \"Unable to close the archive. Error code \\(code)\"\n case .unableToOpenArchive(let code):\n return \"Unable to open the archive. Error code \\(code)\"\n case .unableToSetOption(_):\n return \"Unable to set an option on the archive.\"\n case .failedToSetLocale(let locales):\n return \"Failed to set locale to \\(locales)\"\n case .failedToGetProperty(let path, let propertyName):\n return \"Failed to read property \\(propertyName) from file at path \\(path)\"\n case .failedToDetectFilter:\n return \"Failed to detect filter from archive.\"\n case .failedToDetectFormat:\n return \"Failed to detect format from archive.\"\n case .failedToExtractArchive(let reason):\n return \"Failed to extract archive: \\(reason)\"\n }\n }\n}\n\npublic struct LibArchiveError: Error {\n public let source: ArchiveError\n public let description: String\n}\n\nfunc wrap(_ f: @autoclosure () -> CInt, _ e: (CInt) -> ArchiveError, underlying: OpaquePointer? = nil) throws {\n let result = f()\n guard result == ARCHIVE_OK else {\n let error = e(result)\n guard let underlying = underlying,\n let description = archive_error_string(underlying).map(String.init(cString:))\n else {\n throw error\n }\n throw LibArchiveError(source: error, description: description)\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/IPAddress.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Facilitates conversion between IPv4 address representations.\npublic struct IPv4Address: Codable, CustomStringConvertible, Equatable, Sendable {\n /// The address as a 32-bit integer.\n public let value: UInt32\n\n /// Create an address from a dotted-decimal string, such as \"192.168.64.10\".\n public init(_ fromString: String) throws {\n let split = fromString.components(separatedBy: \".\")\n if split.count != 4 {\n throw NetworkAddressError.invalidStringAddress(address: fromString)\n }\n\n var parsedValue: UInt32 = 0\n for index in 0..<4 {\n guard let octet = UInt8(split[index]) else {\n throw NetworkAddressError.invalidStringAddress(address: fromString)\n }\n parsedValue |= UInt32(octet) << ((3 - index) * 8)\n }\n\n value = parsedValue\n }\n\n /// Create an address from an array of four bytes in network order (big-endian),\n /// such as [192, 168, 64, 10].\n public init(fromNetworkBytes: [UInt8]) throws {\n guard fromNetworkBytes.count == 4 else {\n throw NetworkAddressError.invalidNetworkByteAddress(address: fromNetworkBytes)\n }\n\n value =\n (UInt32(fromNetworkBytes[0]) << 24)\n | (UInt32(fromNetworkBytes[1]) << 16)\n | (UInt32(fromNetworkBytes[2]) << 8)\n | UInt32(fromNetworkBytes[3])\n }\n\n /// Create an address from a 32-bit integer, such as 0xc0a8_400a.\n public init(fromValue: UInt32) {\n value = fromValue\n }\n\n /// Retrieve the address as an array of bytes in network byte order.\n public var networkBytes: [UInt8] {\n [\n UInt8((value >> 24) & 0xff),\n UInt8((value >> 16) & 0xff),\n UInt8((value >> 8) & 0xff),\n UInt8(value & 0xff),\n ]\n }\n\n /// Retrieve the address as a dotted decimal string.\n public var description: String {\n networkBytes.map(String.init).joined(separator: \".\")\n }\n\n /// Create the base IPv4 address for a network that contains this\n /// address and uses the specified subnet mask length.\n public func prefix(prefixLength: PrefixLength) -> IPv4Address {\n IPv4Address(fromValue: value & prefixLength.prefixMask32)\n }\n}\n\nextension IPv4Address {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n let text = try container.decode(String.self)\n try self.init(text)\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n try container.encode(self.description)\n }\n}\n"], ["/containerization/Sources/ContainerizationNetlink/Types.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport Foundation\n\nstruct SocketType {\n static let SOCK_RAW: Int32 = 3\n}\n\nstruct AddressFamily {\n static let AF_UNSPEC: UInt16 = 0\n static let AF_INET: UInt16 = 2\n static let AF_INET6: UInt16 = 10\n static let AF_NETLINK: UInt16 = 16\n static let AF_PACKET: UInt16 = 17\n}\n\nstruct NetlinkProtocol {\n static let NETLINK_ROUTE: Int32 = 0\n}\n\nstruct NetlinkType {\n static let NLMSG_NOOP: UInt16 = 1\n static let NLMSG_ERROR: UInt16 = 2\n static let NLMSG_DONE: UInt16 = 3\n static let NLMSG_OVERRUN: UInt16 = 4\n static let RTM_NEWLINK: UInt16 = 16\n static let RTM_DELLINK: UInt16 = 17\n static let RTM_GETLINK: UInt16 = 18\n static let RTM_NEWADDR: UInt16 = 20\n static let RTM_NEWROUTE: UInt16 = 24\n}\n\nstruct NetlinkFlags {\n static let NLM_F_REQUEST: UInt16 = 0x01\n static let NLM_F_MULTI: UInt16 = 0x02\n static let NLM_F_ACK: UInt16 = 0x04\n static let NLM_F_ECHO: UInt16 = 0x08\n static let NLM_F_DUMP_INTR: UInt16 = 0x10\n static let NLM_F_DUMP_FILTERED: UInt16 = 0x20\n\n // GET request\n static let NLM_F_ROOT: UInt16 = 0x100\n static let NLM_F_MATCH: UInt16 = 0x200\n static let NLM_F_ATOMIC: UInt16 = 0x400\n static let NLM_F_DUMP: UInt16 = NetlinkFlags.NLM_F_ROOT | NetlinkFlags.NLM_F_MATCH\n\n // NEW request flags\n static let NLM_F_REPLACE: UInt16 = 0x100\n static let NLM_F_EXCL: UInt16 = 0x200\n static let NLM_F_CREATE: UInt16 = 0x400\n static let NLM_F_APPEND: UInt16 = 0x800\n}\n\nstruct NetlinkScope {\n static let RT_SCOPE_UNIVERSE: UInt8 = 0\n}\n\nstruct InterfaceFlags {\n static let IFF_UP: UInt32 = 1 << 0\n static let DEFAULT_CHANGE: UInt32 = 0xffff_ffff\n}\n\nstruct LinkAttributeType {\n static let IFLA_EXT_IFNAME: UInt16 = 3\n static let IFLA_MTU: UInt16 = 4\n static let IFLA_EXT_MASK: UInt16 = 29\n}\n\nstruct LinkAttributeMaskFilter {\n static let RTEXT_FILTER_VF: UInt32 = 1 << 0\n static let RTEXT_FILTER_SKIP_STATS: UInt32 = 1 << 3\n}\n\nstruct AddressAttributeType {\n // subnet mask\n static let IFA_ADDRESS: UInt16 = 1\n // IPv4 address\n static let IFA_LOCAL: UInt16 = 2\n}\n\nstruct RouteTable {\n static let MAIN: UInt8 = 254\n}\n\nstruct RouteProtocol {\n static let UNSPEC: UInt8 = 0\n static let REDIRECT: UInt8 = 1\n static let KERNEL: UInt8 = 2\n static let BOOT: UInt8 = 3\n static let STATIC: UInt8 = 4\n}\n\nstruct RouteScope {\n static let UNIVERSE: UInt8 = 0\n static let LINK: UInt8 = 253\n}\n\nstruct RouteType {\n static let UNSPEC: UInt8 = 0\n static let UNICAST: UInt8 = 1\n}\n\nstruct RouteAttributeType {\n static let UNSPEC: UInt16 = 0\n static let DST: UInt16 = 1\n static let SRC: UInt16 = 2\n static let IIF: UInt16 = 3\n static let OIF: UInt16 = 4\n static let GATEWAY: UInt16 = 5\n static let PRIORITY: UInt16 = 6\n static let PREFSRC: UInt16 = 7\n}\n\nprotocol Bindable: Equatable {\n static var size: Int { get }\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int\n}\n\nstruct SockaddrNetlink: Bindable {\n static let size = 12\n\n var family: UInt16\n var pad: UInt16 = 0\n var pid: UInt32\n var groups: UInt32\n\n init(family: UInt16 = 0, pid: UInt32 = 0, groups: UInt32 = 0) {\n self.family = family\n self.pid = pid\n self.groups = groups\n }\n\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let offset = buffer.copyIn(as: UInt16.self, value: family, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: pid, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: groups, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n family = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n pid = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n groups = value\n\n return offset + Self.size\n }\n}\n\nstruct NetlinkMessageHeader: Bindable {\n static let size = 16\n\n var len: UInt32\n var type: UInt16\n var flags: UInt16\n var seq: UInt32\n var pid: UInt32\n\n init(len: UInt32 = 0, type: UInt16 = 0, flags: UInt16 = 0, seq: UInt32? = nil, pid: UInt32 = 0) {\n self.len = len\n self.type = type\n self.flags = flags\n self.seq = seq ?? UInt32.random(in: 0.. Int {\n guard let offset = buffer.copyIn(as: UInt32.self, value: len, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt16.self, value: type, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt16.self, value: flags, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: seq, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: pid, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n len = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n type = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n flags = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n seq = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n pid = value\n\n return offset\n }\n\n var moreResponses: Bool {\n (self.flags & NetlinkFlags.NLM_F_MULTI) != 0\n && (self.type != NetlinkType.NLMSG_DONE && self.type != NetlinkType.NLMSG_ERROR\n && self.type != NetlinkType.NLMSG_OVERRUN)\n }\n}\n\nstruct InterfaceInfo: Bindable {\n static let size = 16\n\n var family: UInt8\n var _pad: UInt8 = 0\n var type: UInt16\n var index: Int32\n var flags: UInt32\n var change: UInt32\n\n init(\n family: UInt8 = UInt8(AddressFamily.AF_UNSPEC), type: UInt16 = 0, index: Int32 = 0, flags: UInt32 = 0,\n change: UInt32 = 0\n ) {\n self.family = family\n self.type = type\n self.index = index\n self.flags = flags\n self.change = change\n }\n\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let offset = buffer.copyIn(as: UInt8.self, value: family, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: _pad, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt16.self, value: type, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: Int32.self, value: index, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: flags, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: change, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n family = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n _pad = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n type = value\n\n guard let (offset, value) = buffer.copyOut(as: Int32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n index = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n flags = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n change = value\n\n return offset\n }\n}\n\nstruct AddressInfo: Bindable {\n static let size = 8\n\n var family: UInt8\n var prefixLength: UInt8\n var flags: UInt8\n var scope: UInt8\n var index: UInt32\n\n init(\n family: UInt8 = UInt8(AddressFamily.AF_UNSPEC), prefixLength: UInt8 = 32, flags: UInt8 = 0, scope: UInt8 = 0,\n index: UInt32 = 0\n ) {\n self.family = family\n self.prefixLength = prefixLength\n self.flags = flags\n self.scope = scope\n self.index = index\n }\n\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let offset = buffer.copyIn(as: UInt8.self, value: family, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: prefixLength, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: flags, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: scope, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: index, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n family = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n prefixLength = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n flags = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n scope = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n index = value\n\n return offset\n }\n}\n\nstruct RouteInfo: Bindable {\n static let size = 12\n\n var family: UInt8\n var dstLen: UInt8\n var srcLen: UInt8\n var tos: UInt8\n var table: UInt8\n var proto: UInt8\n var scope: UInt8\n var type: UInt8\n var flags: UInt32\n\n init(\n family: UInt8 = UInt8(AddressFamily.AF_INET),\n dstLen: UInt8,\n srcLen: UInt8,\n tos: UInt8,\n table: UInt8,\n proto: UInt8,\n scope: UInt8,\n type: UInt8,\n flags: UInt32\n ) {\n self.family = family\n self.dstLen = dstLen\n self.srcLen = srcLen\n self.tos = tos\n self.table = table\n self.proto = proto\n self.scope = scope\n self.type = type\n self.flags = flags\n }\n\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let offset = buffer.copyIn(as: UInt8.self, value: family, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: dstLen, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: srcLen, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: tos, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: table, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: proto, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: scope, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: type, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: flags, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n family = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n dstLen = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n srcLen = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n tos = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n table = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n proto = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n scope = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n type = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n flags = value\n\n return offset\n }\n}\n\n/// A route information.\npublic struct RTAttribute: Bindable {\n static let size = 4\n\n public var len: UInt16\n public var type: UInt16\n public var paddedLen: Int { Int(((len + 3) >> 2) << 2) }\n\n init(len: UInt16 = 0, type: UInt16 = 0) {\n self.len = len\n self.type = type\n }\n\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let offset = buffer.copyIn(as: UInt16.self, value: len, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt16.self, value: type, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n len = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n type = value\n\n return offset\n }\n}\n\n/// A route information with data.\npublic struct RTAttributeData {\n public let attribute: RTAttribute\n public let data: [UInt8]\n}\n\n/// A response from the get link command.\npublic struct LinkResponse {\n public let interfaceIndex: Int32\n public let attrDatas: [RTAttributeData]\n}\n\n/// Errors thrown when parsing netlink data.\npublic enum NetlinkDataError: Swift.Error, CustomStringConvertible, Equatable {\n case sendMarshalFailure\n case recvUnmarshalFailure\n case responseError(rc: Int32)\n case unsupportedPlatform\n\n /// The description of the errors.\n public var description: String {\n switch self {\n case .sendMarshalFailure:\n return \"could not marshal netlink packet\"\n case .recvUnmarshalFailure:\n return \"could not unmarshal netlink packet\"\n case .responseError(let rc):\n return \"netlink response indicates error, rc = \\(rc)\"\n case .unsupportedPlatform:\n return \"unsupported platform\"\n }\n }\n}\n"], ["/containerization/Sources/cctl/cctl+Utils.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\nextension Application {\n static func fetchImage(reference: String, store: ImageStore) async throws -> Containerization.Image {\n do {\n return try await store.get(reference: reference)\n } catch let error as ContainerizationError {\n if error.code == .notFound {\n return try await store.pull(reference: reference)\n }\n throw error\n }\n }\n\n static func parseKeyValuePairs(from items: [String]) -> [String: String] {\n var parsedLabels: [String: String] = [:]\n for item in items {\n let parts = item.split(separator: \"=\", maxSplits: 1)\n guard parts.count == 2 else {\n continue\n }\n let key = String(parts[0])\n let val = String(parts[1])\n parsedLabels[key] = val\n }\n return parsedLabels\n }\n}\n\nextension ContainerizationOCI.Platform {\n static var arm64: ContainerizationOCI.Platform {\n .init(arch: \"arm64\", os: \"linux\", variant: \"v8\")\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/NetworkAddress.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Errors related to IP and CIDR addresses.\npublic enum NetworkAddressError: Swift.Error, Equatable, CustomStringConvertible {\n case invalidStringAddress(address: String)\n case invalidNetworkByteAddress(address: [UInt8])\n case invalidCIDR(cidr: String)\n case invalidAddressForSubnet(address: String, cidr: String)\n case invalidAddressRange(lower: String, upper: String)\n\n public var description: String {\n switch self {\n case .invalidStringAddress(let address):\n return \"invalid IP address string \\(address)\"\n case .invalidNetworkByteAddress(let address):\n return \"invalid IP address bytes \\(address)\"\n case .invalidCIDR(let cidr):\n return \"invalid CIDR block: \\(cidr)\"\n case .invalidAddressForSubnet(let address, let cidr):\n return \"invalid address \\(address) for subnet \\(cidr)\"\n case .invalidAddressRange(let lower, let upper):\n return \"invalid range for addresses \\(lower) and \\(upper)\"\n }\n }\n}\n\npublic typealias PrefixLength = UInt8\n\nextension PrefixLength {\n /// Compute a bit mask that passes the suffix bits, given the network prefix mask length.\n public var suffixMask32: UInt32 {\n if self <= 0 {\n return 0xffff_ffff\n }\n return self >= 32 ? 0x0000_0000 : (1 << (32 - self)) - 1\n }\n\n /// Compute a bit mask that passes the prefix bits, given the network prefix mask length.\n public var prefixMask32: UInt32 {\n ~self.suffixMask32\n }\n\n /// Compute a bit mask that passes the suffix bits, given the network prefix mask length.\n public var suffixMask48: UInt64 {\n if self <= 0 {\n return 0x0000_ffff_ffff_ffff\n }\n return self >= 48 ? 0x0000_0000_0000_0000 : (1 << (48 - self)) - 1\n }\n\n /// Compute a bit mask that passes the prefix bits, given the network prefix mask length.\n public var prefixMask48: UInt64 {\n ~self.suffixMask48 & 0x0000_ffff_ffff_ffff\n }\n}\n"], ["/containerization/Sources/Containerization/AttachedFilesystem.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport ContainerizationOCI\n\n/// A filesystem that was attached and able to be mounted inside the runtime environment.\npublic struct AttachedFilesystem: Sendable {\n /// The type of the filesystem.\n public var type: String\n /// The path to the filesystem within a sandbox.\n public var source: String\n /// Destination when mounting the filesystem inside a sandbox.\n public var destination: String\n /// The options to use when mounting the filesystem.\n public var options: [String]\n\n #if os(macOS)\n public init(mount: Mount, allocator: any AddressAllocator) throws {\n switch mount.type {\n case \"virtiofs\":\n let name = try hashMountSource(source: mount.source)\n self.source = name\n case \"ext4\":\n let char = try allocator.allocate()\n self.source = \"/dev/vd\\(char)\"\n default:\n self.source = mount.source\n }\n self.type = mount.type\n self.options = mount.options\n self.destination = mount.destination\n }\n #endif\n}\n"], ["/containerization/Sources/ContainerizationExtras/Timeout.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// `Timeout` contains helpers to run an operation and error out if\n/// the operation does not finish within a provided time.\npublic struct Timeout {\n /// Performs the passed in `operation` and throws a `CancellationError` if the operation\n /// doesn't finish in the provided `seconds` amount.\n public static func run(\n seconds: UInt32,\n operation: @escaping @Sendable () async -> T\n ) async throws -> T {\n try await withThrowingTaskGroup(of: T.self) { group in\n group.addTask {\n await operation()\n }\n\n group.addTask {\n try await Task.sleep(for: .seconds(seconds))\n throw CancellationError()\n }\n\n guard let result = try await group.next() else {\n fatalError()\n }\n\n group.cancelAll()\n return result\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Socket/SocketType.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if canImport(Musl)\nimport Musl\n#elseif canImport(Glibc)\nimport Glibc\n#elseif canImport(Darwin)\nimport Darwin\n#else\n#error(\"SocketType not supported on this platform.\")\n#endif\n\n/// Protocol used to describe the family of socket to be created with `Socket`.\npublic protocol SocketType: Sendable, CustomStringConvertible {\n /// The domain for the socket (AF_UNIX, AF_VSOCK etc.)\n var domain: Int32 { get }\n /// The type of socket (SOCK_STREAM).\n var type: Int32 { get }\n\n /// Actions to perform before calling bind(2).\n func beforeBind(fd: Int32) throws\n /// Actions to perform before calling listen(2).\n func beforeListen(fd: Int32) throws\n\n /// Handle accept(2) for an implementation of a socket type.\n func accept(fd: Int32) throws -> (Int32, SocketType)\n /// Provide a sockaddr pointer (by casting a socket specific type like sockaddr_un for example).\n func withSockAddr(_ closure: (_ ptr: UnsafePointer, _ len: UInt32) throws -> Void) throws\n}\n\nextension SocketType {\n public func beforeBind(fd: Int32) {}\n public func beforeListen(fd: Int32) {}\n}\n"], ["/containerization/Sources/Containerization/Agent/Vminitd+Rosetta.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\n\nextension Vminitd {\n /// Enable Rosetta's x86_64 emulation.\n public func enableRosetta() async throws {\n let path = \"/run/rosetta\"\n try await self.mount(\n .init(\n type: \"virtiofs\",\n source: \"rosetta\",\n destination: path\n )\n )\n try await self.setupEmulator(\n binaryPath: \"\\(path)/rosetta\",\n configuration: Binfmt.Entry.amd64()\n )\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/UnsafeLittleEndianBytes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n// takes a pointer and converts its contents to native endian bytes\npublic func withUnsafeLittleEndianBytes(of value: T, body: (UnsafeRawBufferPointer) throws -> Result)\n rethrows -> Result\n{\n switch Endian {\n case .little:\n return try withUnsafeBytes(of: value) { bytes in\n try body(bytes)\n }\n case .big:\n return try withUnsafeBytes(of: value) { buffer in\n let reversedBuffer = Array(buffer.reversed())\n return try reversedBuffer.withUnsafeBytes { buf in\n try body(buf)\n }\n }\n }\n}\n\npublic func withUnsafeLittleEndianBuffer(\n of value: UnsafeRawBufferPointer, body: (UnsafeRawBufferPointer) throws -> T\n) rethrows -> T {\n switch Endian {\n case .little:\n return try body(value)\n case .big:\n let reversed = Array(value.reversed())\n return try reversed.withUnsafeBytes { buf in\n try body(buf)\n }\n }\n}\n\nextension UnsafeRawBufferPointer {\n // loads littleEndian raw data, converts it native endian format and calls UnsafeRawBufferPointer.load\n public func loadLittleEndian(as type: T.Type) -> T {\n switch Endian {\n case .little:\n return self.load(as: T.self)\n case .big:\n let buffer = Array(self.reversed())\n return buffer.withUnsafeBytes { ptr in\n ptr.load(as: T.self)\n }\n }\n }\n}\n\npublic enum Endianness {\n case little\n case big\n}\n\n// returns current endianness\npublic var Endian: Endianness {\n switch CFByteOrderGetCurrent() {\n case CFByteOrder(CFByteOrderLittleEndian.rawValue):\n return .little\n case CFByteOrder(CFByteOrderBigEndian.rawValue):\n return .big\n default:\n fatalError(\"impossible\")\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Types.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// swiftlint:disable large_tuple\n\nimport Foundation\n\nextension EXT4 {\n public struct SuperBlock {\n public var inodesCount: UInt32 = 0\n public var blocksCountLow: UInt32 = 0\n public var rootBlocksCountLow: UInt32 = 0\n public var freeBlocksCountLow: UInt32 = 0\n public var freeInodesCount: UInt32 = 0\n public var firstDataBlock: UInt32 = 0\n public var logBlockSize: UInt32 = 0\n public var logClusterSize: UInt32 = 0\n public var blocksPerGroup: UInt32 = 0\n public var clustersPerGroup: UInt32 = 0\n public var inodesPerGroup: UInt32 = 0\n public var mtime: UInt32 = 0\n public var wtime: UInt32 = 0\n public var mountCount: UInt16 = 0\n public var maxMountCount: UInt16 = 0\n public var magic: UInt16 = 0\n public var state: UInt16 = 0\n public var errors: UInt16 = 0\n public var minorRevisionLevel: UInt16 = 0\n public var lastCheck: UInt32 = 0\n public var checkInterval: UInt32 = 0\n public var creatorOS: UInt32 = 0\n public var revisionLevel: UInt32 = 0\n public var defaultReservedUid: UInt16 = 0\n public var defaultReservedGid: UInt16 = 0\n public var firstInode: UInt32 = 0\n public var inodeSize: UInt16 = 0\n public var blockGroupNr: UInt16 = 0\n public var featureCompat: UInt32 = 0\n public var featureIncompat: UInt32 = 0\n public var featureRoCompat: UInt32 = 0\n public var uuid:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var volumeName:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var lastMounted:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var algorithmUsageBitmap: UInt32 = 0\n public var preallocBlocks: UInt8 = 0\n public var preallocDirBlocks: UInt8 = 0\n public var reservedGdtBlocks: UInt16 = 0\n public var journalUUID:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var journalInum: UInt32 = 0\n public var journalDev: UInt32 = 0\n public var lastOrphan: UInt32 = 0\n public var hashSeed: (UInt32, UInt32, UInt32, UInt32) = (0, 0, 0, 0)\n public var defHashVersion: UInt8 = 0\n public var journalBackupType: UInt8 = 0\n public var descSize: UInt16 = UInt16(MemoryLayout.size)\n public var defaultMountOpts: UInt32 = 0\n public var firstMetaBg: UInt32 = 0\n public var mkfsTime: UInt32 = 0\n public var journalBlocks:\n (\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0\n )\n public var blocksCountHigh: UInt32 = 0\n public var rBlocksCountHigh: UInt32 = 0\n public var freeBlocksCountHigh: UInt32 = 0\n public var minExtraIsize: UInt16 = 0\n public var wantExtraIsize: UInt16 = 0\n public var flags: UInt32 = 0\n public var raidStride: UInt16 = 0\n public var mmpInterval: UInt16 = 0\n public var mmpBlock: UInt64 = 0\n public var raidStripeWidth: UInt32 = 0\n public var logGroupsPerFlex: UInt8 = 0\n public var checksumType: UInt8 = 0\n public var reservedPad: UInt16 = 0\n public var kbytesWritten: UInt64 = 0\n public var snapshotInum: UInt32 = 0\n public var snapshotID: UInt32 = 0\n public var snapshotRBlocksCount: UInt64 = 0\n public var snapshotList: UInt32 = 0\n public var errorCount: UInt32 = 0\n public var firstErrorTime: UInt32 = 0\n public var firstErrorInode: UInt32 = 0\n public var firstErrorBlock: UInt64 = 0\n public var firstErrorFunc:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var firstErrorLine: UInt32 = 0\n public var lastErrorTime: UInt32 = 0\n public var lastErrorInode: UInt32 = 0\n public var lastErrorLine: UInt32 = 0\n public var lastErrorBlock: UInt64 = 0\n public var lastErrorFunc:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var mountOpts:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var userQuotaInum: UInt32 = 0\n public var groupQuotaInum: UInt32 = 0\n public var overheadBlocks: UInt32 = 0\n public var backupBgs: (UInt32, UInt32) = (0, 0)\n public var encryptAlgos: (UInt8, UInt8, UInt8, UInt8) = (0, 0, 0, 0)\n public var encryptPwSalt:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var lpfInode: UInt32 = 0\n public var projectQuotaInum: UInt32 = 0\n public var checksumSeed: UInt32 = 0\n public var wtimeHigh: UInt8 = 0\n public var mtimeHigh: UInt8 = 0\n public var mkfsTimeHigh: UInt8 = 0\n public var lastcheckHigh: UInt8 = 0\n public var firstErrorTimeHigh: UInt8 = 0\n public var lastErrorTimeHigh: UInt8 = 0\n public var pad: (UInt8, UInt8) = (0, 0)\n public var reserved:\n (\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var checksum: UInt32 = 0\n }\n\n struct CompatFeature {\n let rawValue: UInt32\n\n static let dirPrealloc = CompatFeature(rawValue: 0x1)\n static let imagicInodes = CompatFeature(rawValue: 0x2)\n static let hasJournal = CompatFeature(rawValue: 0x4)\n static let extAttr = CompatFeature(rawValue: 0x8)\n static let resizeInode = CompatFeature(rawValue: 0x10)\n static let dirIndex = CompatFeature(rawValue: 0x20)\n static let lazyBg = CompatFeature(rawValue: 0x40)\n static let excludeInode = CompatFeature(rawValue: 0x80)\n static let excludeBitmap = CompatFeature(rawValue: 0x100)\n static let sparseSuper2 = CompatFeature(rawValue: 0x200)\n }\n\n struct IncompatFeature {\n let rawValue: UInt32\n\n static let compression = IncompatFeature(rawValue: 0x1)\n static let filetype = IncompatFeature(rawValue: 0x2)\n static let recover = IncompatFeature(rawValue: 0x4)\n static let journalDev = IncompatFeature(rawValue: 0x8)\n static let metaBg = IncompatFeature(rawValue: 0x10)\n static let extents = IncompatFeature(rawValue: 0x40)\n static let bit64 = IncompatFeature(rawValue: 0x80)\n static let mmp = IncompatFeature(rawValue: 0x100)\n static let flexBg = IncompatFeature(rawValue: 0x200)\n static let eaInode = IncompatFeature(rawValue: 0x400)\n static let dirdata = IncompatFeature(rawValue: 0x1000)\n static let csumSeed = IncompatFeature(rawValue: 0x2000)\n static let largedir = IncompatFeature(rawValue: 0x4000)\n static let inlineData = IncompatFeature(rawValue: 0x8000)\n static let encrypt = IncompatFeature(rawValue: 0x10000)\n }\n\n struct RoCompatFeature {\n let rawValue: UInt32\n\n static let sparseSuper = RoCompatFeature(rawValue: 0x1)\n static let largeFile = RoCompatFeature(rawValue: 0x2)\n static let btreeDir = RoCompatFeature(rawValue: 0x4)\n static let hugeFile = RoCompatFeature(rawValue: 0x8)\n static let gdtCsum = RoCompatFeature(rawValue: 0x10)\n static let dirNlink = RoCompatFeature(rawValue: 0x20)\n static let extraIsize = RoCompatFeature(rawValue: 0x40)\n static let hasSnapshot = RoCompatFeature(rawValue: 0x80)\n static let quota = RoCompatFeature(rawValue: 0x100)\n static let bigalloc = RoCompatFeature(rawValue: 0x200)\n static let metadataCsum = RoCompatFeature(rawValue: 0x400)\n static let replica = RoCompatFeature(rawValue: 0x800)\n static let readonly = RoCompatFeature(rawValue: 0x1000)\n static let project = RoCompatFeature(rawValue: 0x2000)\n }\n\n struct BlockGroupFlag {\n let rawValue: UInt16\n\n static let inodeUninit = BlockGroupFlag(rawValue: 0x1)\n static let blockUninit = BlockGroupFlag(rawValue: 0x2)\n static let inodeZeroed = BlockGroupFlag(rawValue: 0x4)\n }\n\n struct GroupDescriptor {\n let blockBitmapLow: UInt32\n let inodeBitmapLow: UInt32\n let inodeTableLow: UInt32\n let freeBlocksCountLow: UInt16\n let freeInodesCountLow: UInt16\n let usedDirsCountLow: UInt16\n let flags: UInt16\n let excludeBitmapLow: UInt32\n let blockBitmapCsumLow: UInt16\n let inodeBitmapCsumLow: UInt16\n let itableUnusedLow: UInt16\n let checksum: UInt16\n }\n\n struct GroupDescriptor64 {\n let groupDescriptor: GroupDescriptor\n let blockBitmapHigh: UInt32\n let inodeBitmapHigh: UInt32\n let inodeTableHigh: UInt32\n let freeBlocksCountHigh: UInt16\n let freeInodesCountHigh: UInt16\n let usedDirsCountHigh: UInt16\n let itableUnusedHigh: UInt16\n let excludeBitmapHigh: UInt32\n let blockBitmapCsumHigh: UInt16\n let inodeBitmapCsumHigh: UInt16\n let reserved: UInt32\n }\n\n public struct FileModeFlag: Sendable {\n let rawValue: UInt16\n\n public static let S_IXOTH = FileModeFlag(rawValue: 0x1)\n public static let S_IWOTH = FileModeFlag(rawValue: 0x2)\n public static let S_IROTH = FileModeFlag(rawValue: 0x4)\n public static let S_IXGRP = FileModeFlag(rawValue: 0x8)\n public static let S_IWGRP = FileModeFlag(rawValue: 0x10)\n public static let S_IRGRP = FileModeFlag(rawValue: 0x20)\n public static let S_IXUSR = FileModeFlag(rawValue: 0x40)\n public static let S_IWUSR = FileModeFlag(rawValue: 0x80)\n public static let S_IRUSR = FileModeFlag(rawValue: 0x100)\n public static let S_ISVTX = FileModeFlag(rawValue: 0x200)\n public static let S_ISGID = FileModeFlag(rawValue: 0x400)\n public static let S_ISUID = FileModeFlag(rawValue: 0x800)\n public static let S_IFIFO = FileModeFlag(rawValue: 0x1000)\n public static let S_IFCHR = FileModeFlag(rawValue: 0x2000)\n public static let S_IFDIR = FileModeFlag(rawValue: 0x4000)\n public static let S_IFBLK = FileModeFlag(rawValue: 0x6000)\n public static let S_IFREG = FileModeFlag(rawValue: 0x8000)\n public static let S_IFLNK = FileModeFlag(rawValue: 0xA000)\n public static let S_IFSOCK = FileModeFlag(rawValue: 0xC000)\n\n public static let TypeMask = FileModeFlag(rawValue: 0xF000)\n }\n\n typealias InodeNumber = UInt32\n\n public struct Inode {\n var mode: UInt16 = 0\n var uid: UInt16 = 0\n var sizeLow: UInt32 = 0\n var atime: UInt32 = 0\n var ctime: UInt32 = 0\n var mtime: UInt32 = 0\n var dtime: UInt32 = 0\n var gid: UInt16 = 0\n var linksCount: UInt16 = 0\n var blocksLow: UInt32 = 0\n var flags: UInt32 = 0\n var version: UInt32 = 0\n var block:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n )\n var generation: UInt32 = 0\n var xattrBlockLow: UInt32 = 0\n var sizeHigh: UInt32 = 0\n var obsoleteFragmentAddr: UInt32 = 0\n var blocksHigh: UInt16 = 0\n var xattrBlockHigh: UInt16 = 0\n var uidHigh: UInt16 = 0\n var gidHigh: UInt16 = 0\n var checksumLow: UInt16 = 0\n var reserved: UInt16 = 0\n var extraIsize: UInt16 = 0\n var checksumHigh: UInt16 = 0\n var ctimeExtra: UInt32 = 0\n var mtimeExtra: UInt32 = 0\n var atimeExtra: UInt32 = 0\n var crtime: UInt32 = 0\n var crtimeExtra: UInt32 = 0\n var versionHigh: UInt32 = 0\n var projid: UInt32 = 0 // Size until this point is 160 bytes\n var inlineXattrs:\n ( // 96 bytes for extended attributes\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0\n )\n\n public static func Mode(_ mode: FileModeFlag, _ perm: UInt16) -> UInt16 {\n mode.rawValue | perm\n }\n }\n\n struct InodeFlag {\n let rawValue: UInt32\n\n static let secRm = InodeFlag(rawValue: 0x1)\n static let unRm = InodeFlag(rawValue: 0x2)\n static let compressed = InodeFlag(rawValue: 0x4)\n static let sync = InodeFlag(rawValue: 0x8)\n static let immutable = InodeFlag(rawValue: 0x10)\n static let append = InodeFlag(rawValue: 0x20)\n static let noDump = InodeFlag(rawValue: 0x40)\n static let noAtime = InodeFlag(rawValue: 0x80)\n static let dirtyCompressed = InodeFlag(rawValue: 0x100)\n static let compressedClusters = InodeFlag(rawValue: 0x200)\n static let noCompress = InodeFlag(rawValue: 0x400)\n static let encrypted = InodeFlag(rawValue: 0x800)\n static let hashedIndex = InodeFlag(rawValue: 0x1000)\n static let magic = InodeFlag(rawValue: 0x2000)\n static let journalData = InodeFlag(rawValue: 0x4000)\n static let noTail = InodeFlag(rawValue: 0x8000)\n static let dirSync = InodeFlag(rawValue: 0x10000)\n static let topDir = InodeFlag(rawValue: 0x20000)\n static let hugeFile = InodeFlag(rawValue: 0x40000)\n static let extents = InodeFlag(rawValue: 0x80000)\n static let eaInode = InodeFlag(rawValue: 0x200000)\n static let eofBlocks = InodeFlag(rawValue: 0x400000)\n static let snapfile = InodeFlag(rawValue: 0x0100_0000)\n static let snapfileDeleted = InodeFlag(rawValue: 0x0400_0000)\n static let snapfileShrunk = InodeFlag(rawValue: 0x0800_0000)\n static let inlineData = InodeFlag(rawValue: 0x1000_0000)\n static let projectIDInherit = InodeFlag(rawValue: 0x2000_0000)\n static let reserved = InodeFlag(rawValue: 0x8000_0000)\n }\n\n struct ExtentHeader {\n let magic: UInt16\n let entries: UInt16\n let max: UInt16\n let depth: UInt16\n let generation: UInt32\n }\n\n struct ExtentIndex {\n let block: UInt32\n let leafLow: UInt32\n let leafHigh: UInt16\n let unused: UInt16\n }\n\n struct ExtentLeaf {\n let block: UInt32\n let length: UInt16\n let startHigh: UInt16\n let startLow: UInt32\n }\n\n struct ExtentTail {\n let checksum: UInt32\n }\n\n struct ExtentIndexNode {\n var header: ExtentHeader\n var indices: [ExtentIndex]\n }\n\n struct ExtentLeafNode {\n var header: ExtentHeader\n var leaves: [ExtentLeaf]\n }\n\n struct DirectoryEntry {\n let inode: InodeNumber\n let recordLength: UInt16\n let nameLength: UInt8\n let fileType: UInt8\n // let name: [UInt8]\n }\n\n enum FileType: UInt8 {\n case unknown = 0x0\n case regular = 0x1\n case directory = 0x2\n case character = 0x3\n case block = 0x4\n case fifo = 0x5\n case socket = 0x6\n case symbolicLink = 0x7\n }\n\n struct DirectoryEntryTail {\n let reservedZero1: UInt32\n let recordLength: UInt16\n let reservedZero2: UInt8\n let fileType: UInt8\n let checksum: UInt32\n }\n\n struct DirectoryTreeRoot {\n let dot: DirectoryEntry\n let dotName: [UInt8]\n let dotDot: DirectoryEntry\n let dotDotName: [UInt8]\n let reservedZero: UInt32\n let hashVersion: UInt8\n let infoLength: UInt8\n let indirectLevels: UInt8\n let unusedFlags: UInt8\n let limit: UInt16\n let count: UInt16\n let block: UInt32\n // let entries: [DirectoryTreeEntry]\n }\n\n struct DirectoryTreeNode {\n let fakeInode: UInt32\n let fakeRecordLength: UInt16\n let nameLength: UInt8\n let fileType: UInt8\n let limit: UInt16\n let count: UInt16\n let block: UInt32\n // let entries: [DirectoryTreeEntry]\n }\n\n struct DirectoryTreeEntry {\n let hash: UInt32\n let block: UInt32\n }\n\n struct DirectoryTreeTail {\n let reserved: UInt32\n let checksum: UInt32\n }\n\n struct XAttrEntry {\n let nameLength: UInt8\n let nameIndex: UInt8\n let valueOffset: UInt16\n let valueInum: UInt32\n let valueSize: UInt32\n let hash: UInt32\n }\n\n struct XAttrHeader {\n let magic: UInt32\n let referenceCount: UInt32\n let blocks: UInt32\n let hash: UInt32\n let checksum: UInt32\n let reserved: [UInt32]\n }\n\n}\n\nextension EXT4.Inode {\n public static func Root() -> EXT4.Inode {\n var inode = Self() // inode\n inode.mode = Self.Mode(.S_IFDIR, 0o755)\n inode.linksCount = 2\n inode.uid = 0\n inode.gid = 0\n // time\n let now = Date().fs()\n let now_lo: UInt32 = now.lo\n let now_hi: UInt32 = now.hi\n inode.atime = now_lo\n inode.atimeExtra = now_hi\n inode.ctime = now_lo\n inode.ctimeExtra = now_hi\n inode.mtime = now_lo\n inode.mtimeExtra = now_hi\n inode.crtime = now_lo\n inode.crtimeExtra = now_hi\n inode.flags = EXT4.InodeFlag.hugeFile.rawValue\n inode.extraIsize = UInt16(EXT4.ExtraIsize)\n return inode\n }\n}\n"], ["/containerization/Sources/Containerization/IO/Terminal+ReaderStream.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\n\nextension Terminal: ReaderStream {\n public func stream() -> AsyncStream {\n .init { cont in\n self.handle.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n self.handle.readabilityHandler = nil\n cont.finish()\n return\n }\n cont.yield(data)\n }\n }\n }\n}\n\nextension Terminal: Writer {}\n"], ["/containerization/Sources/ContainerizationError/ContainerizationError.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// The core error type for Containerization.\n///\n/// Most API surfaces for the core container/process/agent types will\n/// return a ContainerizationError.\npublic struct ContainerizationError: Swift.Error, Sendable {\n /// A code describing the error encountered.\n public var code: Code\n /// A description of the error.\n public var message: String\n /// The original error which led to this error being thrown.\n public var cause: (any Error)?\n\n /// Creates a new error.\n ///\n /// - Parameters:\n /// - code: The error code.\n /// - message: A description of the error.\n /// - cause: The original error which led to this error being thrown.\n public init(_ code: Code, message: String, cause: (any Error)? = nil) {\n self.code = code\n self.message = message\n self.cause = cause\n }\n\n /// Creates a new error.\n ///\n /// - Parameters:\n /// - rawCode: The error code value as a String.\n /// - message: A description of the error.\n /// - cause: The original error which led to this error being thrown.\n public init(_ rawCode: String, message: String, cause: (any Error)? = nil) {\n self.code = Code(rawValue: rawCode)\n self.message = message\n self.cause = cause\n }\n\n /// Provides a unique hash of the error.\n public func hash(into hasher: inout Hasher) {\n hasher.combine(self.code)\n hasher.combine(self.message)\n }\n\n /// Equality operator for the error. Uses the code and message.\n public static func == (lhs: Self, rhs: Self) -> Bool {\n lhs.code == rhs.code && lhs.message == rhs.message\n }\n\n /// Checks if the given error has the provided code.\n public func isCode(_ code: Code) -> Bool {\n self.code == code\n }\n}\n\nextension ContainerizationError: CustomStringConvertible {\n /// Description of the error.\n public var description: String {\n guard let cause = self.cause else {\n return \"\\(self.code): \\\"\\(self.message)\\\"\"\n }\n return \"\\(self.code): \\\"\\(self.message)\\\" (cause: \\\"\\(cause)\\\")\"\n }\n}\n\nextension ContainerizationError {\n /// Codes for a `ContainerizationError`.\n public struct Code: Sendable, Hashable {\n private enum Value: Hashable, Sendable, CaseIterable {\n case unknown\n case invalidArgument\n case internalError\n case exists\n case notFound\n case cancelled\n case invalidState\n case empty\n case timeout\n case unsupported\n case interrupted\n }\n\n private var value: Value\n private init(_ value: Value) {\n self.value = value\n }\n\n init(rawValue: String) {\n let values = Value.allCases.reduce(into: [String: Value]()) {\n $0[String(describing: $1)] = $1\n }\n\n let match = values[rawValue]\n guard let match else {\n fatalError(\"invalid Code Value \\(rawValue)\")\n }\n self.value = match\n }\n\n public static var unknown: Self {\n Self(.unknown)\n }\n\n public static var invalidArgument: Self {\n Self(.invalidArgument)\n }\n\n public static var internalError: Self {\n Self(.internalError)\n }\n\n public static var exists: Self {\n Self(.exists)\n }\n\n public static var notFound: Self {\n Self(.notFound)\n }\n\n public static var cancelled: Self {\n Self(.cancelled)\n }\n\n public static var invalidState: Self {\n Self(.invalidState)\n }\n\n public static var empty: Self {\n Self(.empty)\n }\n\n public static var timeout: Self {\n Self(.timeout)\n }\n\n public static var unsupported: Self {\n Self(.unsupported)\n }\n\n public static var interrupted: Self {\n Self(.interrupted)\n }\n }\n}\n\nextension ContainerizationError.Code: CustomStringConvertible {\n public var description: String {\n String(describing: self.value)\n }\n}\n"], ["/containerization/Sources/Containerization/HostsConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Static table lookups for a container. The values will be used to\n/// construct /etc/hosts for a given container.\npublic struct Hosts: Sendable {\n /// Represents one entry in an /etc/hosts file.\n public struct Entry: Sendable {\n /// The IPV4 or IPV6 address in String form.\n public var ipAddress: String\n /// The hostname(s) for the entry.\n public var hostnames: [String]\n /// An optional comment to be placed to the right side of the entry.\n public var comment: String?\n\n public init(ipAddress: String, hostnames: [String], comment: String? = nil) {\n self.comment = comment\n self.hostnames = hostnames\n self.ipAddress = ipAddress\n }\n\n /// The information in the structure rendered to a String representation\n /// that matches the format /etc/hosts expects.\n public var rendered: String {\n var line = ipAddress\n if !hostnames.isEmpty {\n line += \" \" + hostnames.joined(separator: \" \")\n }\n if let comment {\n line += \" # \\(comment) \"\n }\n return line\n }\n\n public static func localHostIPV4(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"127.0.0.1\",\n hostnames: [\"localhost\"],\n comment: comment\n )\n }\n\n public static func localHostIPV6(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"::1\",\n hostnames: [\"localhost\", \"ip6-localhost\", \"ip6-loopback\"],\n comment: comment\n )\n }\n\n public static func ipv6LocalNet(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"fe00::\",\n hostnames: [\"ip6-localnet\"],\n comment: comment\n )\n }\n\n public static func ipv6MulticastPrefix(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"ff00::\",\n hostnames: [\"ip6-mcastprefix\"],\n comment: comment\n )\n }\n\n public static func ipv6AllNodes(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"ff02::1\",\n hostnames: [\"ip6-allnodes\"],\n comment: comment\n )\n }\n\n public static func ipv6AllRouters(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"ff02::2\",\n hostnames: [\"ip6-allrouters\"],\n comment: comment\n )\n }\n }\n\n /// The entries to be written to /etc/hosts.\n public var entries: [Entry]\n\n /// A comment to render at the top of the file.\n public var comment: String?\n\n public init(\n entries: [Entry],\n comment: String? = nil\n ) {\n self.entries = entries\n self.comment = comment\n }\n}\n\nextension Hosts {\n /// A default entry that can be used for convenience. It contains a IPV4\n /// and IPV6 localhost entry, as well as ipv6 localnet, ipv6 mcastprefix,\n /// ipv6 allnodes, and ipv6 allrouters.\n public static let `default` = Hosts(entries: [\n Entry.localHostIPV4(),\n Entry.localHostIPV6(),\n Entry.ipv6LocalNet(),\n Entry.ipv6MulticastPrefix(),\n Entry.ipv6AllNodes(),\n Entry.ipv6AllRouters(),\n ])\n\n /// Returns a string variant of the data that can be written to\n /// /etc/hosts directly.\n public var hostsFile: String {\n var lines: [String] = []\n\n if let comment {\n lines.append(\"# \\(comment)\")\n }\n\n for entry in entries {\n lines.append(entry.rendered)\n }\n\n return lines.joined(separator: \"\\n\") + \"\\n\"\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/Integer+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension UInt64 {\n public var lo: UInt32 {\n UInt32(self & 0xffff_ffff)\n }\n\n public var hi: UInt32 {\n UInt32(self >> 32)\n }\n\n public static func - (lhs: Self, rhs: UInt32) -> UInt64 {\n lhs - UInt64(rhs)\n }\n\n public static func % (lhs: Self, rhs: UInt32) -> UInt64 {\n lhs % UInt64(rhs)\n }\n\n public static func / (lhs: Self, rhs: UInt32) -> UInt32 {\n (lhs / UInt64(rhs)).lo\n }\n\n public static func * (lhs: Self, rhs: UInt32) -> UInt64 {\n lhs * UInt64(rhs)\n }\n\n public static func * (lhs: Self, rhs: Int) -> UInt64 {\n lhs * UInt64(rhs)\n }\n}\n\nextension UInt32 {\n public var lo: UInt16 {\n UInt16(self & 0xffff)\n }\n\n public var hi: UInt16 {\n UInt16(self >> 16)\n }\n\n public static func + (lhs: Self, rhs: Int.IntegerLiteralType) -> UInt32 {\n lhs + UInt32(rhs)\n }\n\n public static func - (lhs: Self, rhs: Int.IntegerLiteralType) -> UInt32 {\n lhs - UInt32(rhs)\n }\n\n public static func / (lhs: Self, rhs: Int.IntegerLiteralType) -> UInt32 {\n lhs / UInt32(rhs)\n }\n\n public static func - (lhs: Self, rhs: UInt16) -> UInt32 {\n lhs - UInt32(rhs)\n }\n\n public static func * (lhs: Self, rhs: Int.IntegerLiteralType) -> Int {\n Int(lhs) * rhs\n }\n}\n\nextension Int {\n public static func + (lhs: Self, rhs: UInt32) -> Int {\n lhs + Int(rhs)\n }\n\n public static func + (lhs: Self, rhs: UInt32) -> UInt32 {\n UInt32(lhs) + rhs\n }\n}\n\nextension UInt16 {\n func isDir() -> Bool {\n self & EXT4.FileModeFlag.TypeMask.rawValue == EXT4.FileModeFlag.S_IFDIR.rawValue\n }\n\n func isLink() -> Bool {\n self & EXT4.FileModeFlag.TypeMask.rawValue == EXT4.FileModeFlag.S_IFLNK.rawValue\n }\n\n func isReg() -> Bool {\n self & EXT4.FileModeFlag.TypeMask.rawValue == EXT4.FileModeFlag.S_IFREG.rawValue\n }\n\n func fileType() -> UInt8 {\n typealias FMode = EXT4.FileModeFlag\n typealias FileType = EXT4.FileType\n switch self & FMode.TypeMask.rawValue {\n case FMode.S_IFREG.rawValue:\n return FileType.regular.rawValue\n case FMode.S_IFDIR.rawValue:\n return FileType.directory.rawValue\n case FMode.S_IFCHR.rawValue:\n return FileType.character.rawValue\n case FMode.S_IFBLK.rawValue:\n return FileType.block.rawValue\n case FMode.S_IFIFO.rawValue:\n return FileType.fifo.rawValue\n case FMode.S_IFSOCK.rawValue:\n return FileType.socket.rawValue\n case FMode.S_IFLNK.rawValue:\n return FileType.symbolicLink.rawValue\n default:\n return FileType.unknown.rawValue\n }\n }\n}\n\nextension [UInt8] {\n var allZeros: Bool {\n for num in self where num != 0 {\n return false\n }\n return true\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Signals.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Helper type with utilities to parse and manipulate unix signals.\npublic struct Signals {\n /// Returns the numeric values of all known signals.\n public static func allNumeric() -> [Int32] {\n Array(Signals.all.values)\n }\n\n /// Parses a string representation of a signal (SIGKILL) and returns\n // the 32 bit integer representation (9).\n public static func parseSignal(_ signal: String) throws -> Int32 {\n if let sig = Int32(signal) {\n if !Signals.all.values.contains(sig) {\n throw Error.invalidSignal(signal)\n }\n return sig\n }\n var signalUpper = signal.uppercased()\n signalUpper.trimPrefix(\"SIG\")\n guard let sig = Signals.all[signalUpper] else {\n throw Error.invalidSignal(signal)\n }\n return sig\n }\n\n /// Errors that can be encountered for converting signals.\n public enum Error: Swift.Error, CustomStringConvertible {\n case invalidSignal(String)\n\n public var description: String {\n switch self {\n case .invalidSignal(let sig):\n return \"invalid signal: \\(sig)\"\n }\n }\n }\n}\n\n#if os(macOS)\n\nextension Signals {\n /// `all` returns all signals for the current platform.\n public static let all: [String: Int32] = [\n \"ABRT\": SIGABRT,\n \"ALRM\": SIGALRM,\n \"BUS\": SIGBUS,\n \"CHLD\": SIGCHLD,\n \"CONT\": SIGCONT,\n \"EMT\": SIGEMT,\n \"FPE\": SIGFPE,\n \"HUP\": SIGHUP,\n \"ILL\": SIGILL,\n \"INFO\": SIGINFO,\n \"INT\": SIGINT,\n \"IO\": SIGIO,\n \"IOT\": SIGIOT,\n \"KILL\": SIGKILL,\n \"PIPE\": SIGPIPE,\n \"PROF\": SIGPROF,\n \"QUIT\": SIGQUIT,\n \"SEGV\": SIGSEGV,\n \"STOP\": SIGSTOP,\n \"SYS\": SIGSYS,\n \"TERM\": SIGTERM,\n \"TRAP\": SIGTRAP,\n \"TSTP\": SIGTSTP,\n \"TTIN\": SIGTTIN,\n \"TTOU\": SIGTTOU,\n \"URG\": SIGURG,\n \"USR1\": SIGUSR1,\n \"USR2\": SIGUSR2,\n \"VTALRM\": SIGVTALRM,\n \"WINCH\": SIGWINCH,\n \"XCPU\": SIGXCPU,\n \"XFSZ\": SIGXFSZ,\n ]\n}\n\n#endif\n\n#if os(Linux)\n\nextension Signals {\n /// `all` returns all signals for the current platform.\n ///\n /// For Linux this isn't actually exhaustive as it excludes\n /// rtmin/rtmax entries.\n public static let all: [String: Int32] = [\n \"ABRT\": SIGABRT,\n \"ALRM\": SIGALRM,\n \"BUS\": SIGBUS,\n \"CHLD\": SIGCHLD,\n \"CLD\": SIGCHLD,\n \"CONT\": SIGCONT,\n \"FPE\": SIGFPE,\n \"HUP\": SIGHUP,\n \"ILL\": SIGILL,\n \"INT\": SIGINT,\n \"IO\": SIGIO,\n \"IOT\": SIGIOT,\n \"KILL\": SIGKILL,\n \"PIPE\": SIGPIPE,\n \"POLL\": SIGPOLL,\n \"PROF\": SIGPROF,\n \"PWR\": SIGPWR,\n \"QUIT\": SIGQUIT,\n \"SEGV\": SIGSEGV,\n \"STKFLT\": SIGSTKFLT,\n \"STOP\": SIGSTOP,\n \"SYS\": SIGSYS,\n \"TERM\": SIGTERM,\n \"TRAP\": SIGTRAP,\n \"TSTP\": SIGTSTP,\n \"TTIN\": SIGTTIN,\n \"TTOU\": SIGTTOU,\n \"URG\": SIGURG,\n \"USR1\": SIGUSR1,\n \"USR2\": SIGUSR2,\n \"VTALRM\": SIGVTALRM,\n \"WINCH\": SIGWINCH,\n \"XCPU\": SIGXCPU,\n \"XFSZ\": SIGXFSZ,\n ]\n}\n\n#endif\n"], ["/containerization/Sources/ContainerizationExtras/AddressAllocator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Conforming objects can allocate and free various address types.\npublic protocol AddressAllocator: Sendable {\n associatedtype AddressType: Sendable\n\n /// Allocate a new address.\n func allocate() throws -> AddressType\n\n /// Attempt to reserve a specific address.\n func reserve(_ address: AddressType) throws\n\n /// Free an allocated address.\n func release(_ address: AddressType) throws\n\n /// If no addresses are allocated, prevent future allocations and return true.\n func disableAllocator() -> Bool\n}\n\n/// Errors that a type implementing AddressAllocator should throw.\npublic enum AllocatorError: Swift.Error, CustomStringConvertible, Equatable {\n case allocatorDisabled\n case allocatorFull\n case alreadyAllocated(_ address: String)\n case invalidAddress(_ index: String)\n case invalidArgument(_ msg: String)\n case invalidIndex(_ index: Int)\n case notAllocated(_ address: String)\n case rangeExceeded\n\n public var description: String {\n switch self {\n case .allocatorDisabled:\n return \"the allocator is shutting down\"\n case .allocatorFull:\n return \"no free indices are available for allocation\"\n case .alreadyAllocated(let address):\n return \"cannot choose already-allocated address \\(address)\"\n case .invalidAddress(let address):\n return \"cannot create index using address \\(address)\"\n case .invalidArgument(let msg):\n return \"invalid argument: \\(msg)\"\n case .invalidIndex(let index):\n return \"cannot create address using index \\(index)\"\n case .notAllocated(let address):\n return \"cannot free unallocated address \\(address)\"\n case .rangeExceeded:\n return \"cannot create allocator that overflows maximum address value\"\n }\n }\n}\n"], ["/containerization/Sources/Containerization/UnixSocketConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\n/// Represents a UnixSocket that can be shared into or out of a container/guest.\npublic struct UnixSocketConfiguration: Sendable {\n // TODO: Realistically, we can just hash this struct and use it as the \"id\".\n package var id: String {\n _id\n }\n\n private let _id = UUID().uuidString\n\n /// The path to the socket you'd like relayed. For .into\n /// direction this should be the path on the host to a unix socket.\n /// For direction .outOf this should be the path in the container/guest\n /// to a unix socket.\n public var source: URL\n\n /// The path you'd like the socket to be relayed to. For .into\n /// direction this should be the path in the container/guest. For\n /// direction .outOf this should be the path on your host.\n public var destination: URL\n\n /// What to set the file permissions of the unix socket being created\n /// to. For .into direction this will be the socket in the guest. For\n /// .outOf direction this will be the socket on the host.\n public var permissions: FilePermissions?\n\n /// The direction of the relay. `.into` for sharing a unix socket on your\n /// host into the container/guest. `outOf` shares a socket in the container/guest\n /// onto your host.\n public var direction: Direction\n\n /// Type that denotes the direction of the unix socket relay.\n public enum Direction: Sendable {\n /// Share the socket into the container/guest.\n case into\n /// Share a socket in the container/guest onto the host.\n case outOf\n }\n\n public init(\n source: URL,\n destination: URL,\n permissions: FilePermissions? = nil,\n direction: Direction = .into\n ) {\n self.source = source\n self.destination = destination\n self.permissions = permissions\n self.direction = direction\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Ptr.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension EXT4 {\n class Ptr {\n let underlying: UnsafeMutablePointer\n private var capacity: Int\n private var initialized: Bool\n private var allocated: Bool\n\n var pointee: T {\n underlying.pointee\n }\n\n init(capacity: Int) {\n self.underlying = UnsafeMutablePointer.allocate(capacity: capacity)\n self.capacity = capacity\n self.allocated = true\n self.initialized = false\n }\n\n static func allocate(capacity: Int) -> Ptr {\n Ptr(capacity: capacity)\n }\n\n func initialize(to value: T) {\n guard self.allocated else {\n return\n }\n if self.initialized {\n self.underlying.deinitialize(count: self.capacity)\n }\n self.underlying.initialize(to: value)\n self.allocated = true\n self.initialized = true\n }\n\n func deallocate() {\n guard self.allocated else {\n return\n }\n self.underlying.deallocate()\n self.allocated = false\n self.initialized = false\n }\n\n func deinitialize(count: Int) {\n guard self.allocated else {\n return\n }\n guard self.initialized else {\n return\n }\n self.underlying.deinitialize(count: count)\n self.initialized = false\n self.allocated = true\n }\n\n func move() -> T {\n self.initialized = false\n self.allocated = true\n return self.underlying.move()\n }\n\n deinit {\n self.deinitialize(count: self.capacity)\n self.deallocate()\n }\n }\n}\n"], ["/containerization/Sources/Containerization/Kernel.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// An object representing a Linux kernel used to boot a virtual machine.\n/// In addition to a path to the kernel itself, this type stores relevant\n/// data such as the commandline to pass to the kernel, and init arguments.\npublic struct Kernel: Sendable, Codable {\n /// The command line arguments passed to the kernel on boot.\n public struct CommandLine: Sendable, Codable {\n public static let kernelDefaults = [\n \"console=hvc0\",\n \"tsc=reliable\",\n ]\n\n /// Adds the debug argument to the kernel commandline.\n mutating public func addDebug() {\n self.kernelArgs.append(\"debug\")\n }\n\n /// Adds a panic level to the kernel commandline.\n mutating public func addPanic(level: Int) {\n self.kernelArgs.append(\"panic=\\(level)\")\n }\n\n /// Additional kernel arguments.\n public var kernelArgs: [String]\n /// Additional arguments passed to the Initial Process / Agent.\n public var initArgs: [String]\n\n /// Initializes the kernel commandline using the mix of kernel arguments\n /// and init arguments.\n public init(\n kernelArgs: [String] = kernelDefaults,\n initArgs: [String] = []\n ) {\n self.kernelArgs = kernelArgs\n self.initArgs = initArgs\n }\n\n /// Initializes the kernel commandline to the defaults of Self.kernelDefaults,\n /// adds a debug and panic flag as instructed, and optionally a set of init\n /// process flags to supply to vminitd.\n public init(debug: Bool, panic: Int, initArgs: [String] = []) {\n var args = Self.kernelDefaults\n if debug {\n args.append(\"debug\")\n }\n args.append(\"panic=\\(panic)\")\n self.kernelArgs = args\n self.initArgs = initArgs\n }\n }\n\n /// Path on disk to the kernel binary.\n public var path: URL\n /// Platform for the kernel.\n public var platform: SystemPlatform\n /// Kernel and init process command line.\n public var commandLine: Self.CommandLine\n\n /// Kernel command line arguments.\n public var kernelArgs: [String] {\n self.commandLine.kernelArgs\n }\n\n /// Init process arguments.\n public var initArgs: [String] {\n self.commandLine.initArgs\n }\n\n public init(\n path: URL,\n platform: SystemPlatform,\n commandline: Self.CommandLine = CommandLine(debug: false, panic: 0)\n ) {\n self.path = path\n self.platform = platform\n self.commandLine = commandline\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/UInt8+DataBinding.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension ArraySlice {\n package func hexEncodedString() -> String {\n self.map { String(format: \"%02hhx\", $0) }.joined()\n }\n}\n\nextension [UInt8] {\n package func hexEncodedString() -> String {\n self.map { String(format: \"%02hhx\", $0) }.joined()\n }\n\n package mutating func bind(as type: T.Type, offset: Int = 0, size: Int? = nil) -> UnsafeMutablePointer? {\n guard self.count >= (size ?? MemoryLayout.size) + offset else {\n return nil\n }\n\n return self.withUnsafeMutableBytes { $0.baseAddress?.advanced(by: offset).assumingMemoryBound(to: T.self) }\n }\n\n package mutating func copyIn(as type: T.Type, value: T, offset: Int = 0, size: Int? = nil) -> Int? {\n let size = size ?? MemoryLayout.size\n guard self.count >= size - offset else {\n return nil\n }\n\n return self.withUnsafeMutableBytes {\n $0.baseAddress?.advanced(by: offset).assumingMemoryBound(to: T.self).pointee = value\n return offset + MemoryLayout.size\n }\n }\n\n package mutating func copyOut(as type: T.Type, offset: Int = 0, size: Int? = nil) -> (Int, T)? {\n guard self.count >= (size ?? MemoryLayout.size) - offset else {\n return nil\n }\n\n return self.withUnsafeMutableBytes {\n guard let value = $0.baseAddress?.advanced(by: offset).assumingMemoryBound(to: T.self).pointee else {\n return nil\n }\n return (offset + MemoryLayout.size, value)\n }\n }\n\n package mutating func copyIn(buffer: [UInt8], offset: Int = 0) -> Int? {\n guard offset + buffer.count <= self.count else {\n return nil\n }\n\n self[offset.. Int? {\n guard offset + buffer.count <= self.count else {\n return nil\n }\n\n buffer[0.. Int64? {\n do {\n let attributes = try attributesOfItem(atPath: path)\n guard let fileSize = attributes[.size] as? NSNumber else {\n return nil\n }\n return fileSize.int64Value\n } catch {\n return nil\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/ImageConfig.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// Source: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/config.go\n\nimport Foundation\n\n/// ImageConfig defines the execution parameters which should be used as a base when running a container using an image.\npublic struct ImageConfig: Codable, Sendable {\n enum CodingKeys: String, CodingKey {\n case user = \"User\"\n case env = \"Env\"\n case entrypoint = \"Entrypoint\"\n case cmd = \"Cmd\"\n case workingDir = \"WorkingDir\"\n case labels = \"Labels\"\n case stopSignal = \"StopSignal\"\n }\n\n /// user defines the username or UID which the process in the container should run as.\n public let user: String?\n\n /// env is a list of environment variables to be used in a container.\n public let env: [String]?\n\n /// entrypoint defines a list of arguments to use as the command to execute when the container starts.\n public let entrypoint: [String]?\n\n /// cmd defines the default arguments to the entrypoint of the container.\n public let cmd: [String]?\n\n /// workingDir sets the current working directory of the entrypoint process in the container.\n public let workingDir: String?\n\n /// labels contains arbitrary metadata for the container.\n public let labels: [String: String]?\n\n /// stopSignal contains the system call signal that will be sent to the container to exit.\n public let stopSignal: String?\n\n public init(\n user: String? = nil, env: [String]? = nil, entrypoint: [String]? = nil, cmd: [String]? = nil,\n workingDir: String? = nil, labels: [String: String]? = nil, stopSignal: String? = nil\n ) {\n self.user = user\n self.env = env\n self.entrypoint = entrypoint\n self.cmd = cmd\n self.workingDir = workingDir\n self.labels = labels\n self.stopSignal = stopSignal\n }\n}\n\n/// RootFS describes a layer content addresses\npublic struct Rootfs: Codable, Sendable {\n enum CodingKeys: String, CodingKey {\n case type\n case diffIDs = \"diff_ids\"\n }\n\n /// type is the type of the rootfs.\n public let type: String\n\n /// diffIDs is an array of layer content hashes (DiffIDs), in order from bottom-most to top-most.\n public let diffIDs: [String]\n\n public init(type: String, diffIDs: [String]) {\n self.type = type\n self.diffIDs = diffIDs\n }\n}\n\n/// History describes the history of a layer.\npublic struct History: Codable, Sendable {\n enum CodingKeys: String, CodingKey {\n case created\n case createdBy = \"created_by\"\n case author\n case comment\n case emptyLayer = \"empty_layer\"\n }\n\n /// created is the combined date and time at which the layer was created, formatted as defined by RFC 3339, section 5.6.\n public let created: String?\n\n /// createdBy is the command which created the layer.\n public let createdBy: String?\n\n /// author is the author of the build point.\n public let author: String?\n\n /// comment is a custom message set when creating the layer.\n public let comment: String?\n\n /// emptyLayer is used to mark if the history item created a filesystem diff.\n public let emptyLayer: Bool?\n\n public init(\n created: String? = nil, createdBy: String? = nil, author: String? = nil, comment: String? = nil,\n emptyLayer: Bool? = nil\n ) {\n self.created = created\n self.createdBy = createdBy\n self.author = author\n self.comment = comment\n self.emptyLayer = emptyLayer\n }\n}\n\n/// Image is the JSON structure which describes some basic information about the image.\n/// This provides the `application/vnd.oci.image.config.v1+json` mediatype when marshalled to JSON.\npublic struct Image: Codable, Sendable {\n /// created is the combined date and time at which the image was created, formatted as defined by RFC 3339, section 5.6.\n public let created: String?\n\n /// author defines the name and/or email address of the person or entity which created and is responsible for maintaining the image.\n public let author: String?\n\n /// architecture field specifies the CPU architecture, for example `amd64` or `ppc64`.\n public let architecture: String\n\n /// os specifies the operating system, for example `linux` or `windows`.\n public let os: String\n\n /// osVersion is an optional field specifying the operating system version, for example on Windows `10.0.14393.1066`.\n public let osVersion: String?\n\n /// osFeatures is an optional field specifying an array of strings, each listing a required OS feature (for example on Windows `win32k`).\n public let osFeatures: [String]?\n\n /// variant is an optional field specifying a variant of the CPU, for example `v7` to specify ARMv7 when architecture is `arm`.\n public let variant: String?\n\n /// config defines the execution parameters which should be used as a base when running a container using the image.\n public let config: ImageConfig?\n\n /// rootfs references the layer content addresses used by the image.\n public let rootfs: Rootfs\n\n /// history describes the history of each layer.\n public let history: [History]?\n\n public init(\n created: String? = nil, author: String? = nil, architecture: String, os: String, osVersion: String? = nil,\n osFeatures: [String]? = nil, variant: String? = nil, config: ImageConfig? = nil, rootfs: Rootfs,\n history: [History]? = nil\n ) {\n self.created = created\n self.author = author\n self.architecture = architecture\n self.os = os\n self.osVersion = osVersion\n self.osFeatures = osFeatures\n self.variant = variant\n self.config = config\n self.rootfs = rootfs\n self.history = history\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Reaper.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A process reaper that returns exited processes along\n/// with their exit status.\npublic struct Reaper {\n /// Process's pid and exit status.\n typealias Exit = (pid: Int32, status: Int32)\n\n /// Reap all pending processes and return the pid and exit status.\n public static func reap() -> [Int32: Int32] {\n var reaped = [Int32: Int32]()\n while true {\n guard let exit = wait() else {\n return reaped\n }\n reaped[exit.pid] = exit.status\n }\n return reaped\n }\n\n /// Returns the exit status of the last process that exited.\n /// nil is returned when no pending processes exist.\n private static func wait() -> Exit? {\n var rus = rusage()\n var ws = Int32()\n\n let pid = wait4(-1, &ws, WNOHANG, &rus)\n if pid <= 0 {\n return nil\n }\n return (pid: pid, status: Command.toExitStatus(ws))\n }\n}\n"], ["/containerization/Sources/SendableProperty/Synchronized.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// `Synchronization` will be automatically imported with `SendableProperty`.\n@_exported import Synchronization\n\n/// A synchronization primitive that protects shared mutable state via mutual exclusion.\npublic final class Synchronized: Sendable {\n private let lock: Mutex\n\n private struct State: @unchecked Sendable {\n var value: T\n }\n\n /// Creates a new instance.\n /// - Parameter value: The initial value.\n public init(_ value: T) {\n self.lock = Mutex(State(value: value))\n }\n\n /// Calls the given closure after acquiring the lock and returns its value.\n /// - Parameter body: The body of code to execute while the lock is held.\n public func withLock(_ body: (inout T) throws -> R) rethrows -> R {\n try lock.withLock { state in\n try body(&state.value)\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/State.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum ContainerState: String, Codable, Sendable {\n case creating\n case created\n case running\n case stopped\n}\n\npublic struct State: Codable, Sendable {\n public init(\n version: String,\n id: String,\n status: ContainerState,\n pid: Int,\n bundle: String,\n annotations: [String: String]?\n ) {\n self.ociVersion = version\n self.id = id\n self.status = status\n self.pid = pid\n self.bundle = bundle\n self.annotations = annotations\n }\n\n public init(instance: State) {\n self.ociVersion = instance.ociVersion\n self.id = instance.id\n self.status = instance.status\n self.pid = instance.pid\n self.bundle = instance.bundle\n self.annotations = instance.annotations\n }\n\n public let ociVersion: String\n public let id: String\n public let status: ContainerState\n public let pid: Int\n public let bundle: String\n public var annotations: [String: String]?\n}\n\npublic let seccompFdName: String = \"seccompFd\"\n\npublic struct ContainerProcessState: Codable, Sendable {\n public init(version: String, fds: [String], pid: Int, metadata: String, state: State) {\n self.ociVersion = version\n self.fds = fds\n self.pid = pid\n self.metadata = metadata\n self.state = state\n }\n\n public init(instance: ContainerProcessState) {\n self.ociVersion = instance.ociVersion\n self.fds = instance.fds\n self.pid = instance.pid\n self.metadata = instance.metadata\n self.state = instance.state\n }\n\n public let ociVersion: String\n public var fds: [String]\n public let pid: Int\n public let metadata: String\n public let state: State\n}\n"], ["/containerization/Sources/ContainerizationOCI/Manifest.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// Source: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/manifest.go\n\nimport Foundation\n\n/// Manifest provides `application/vnd.oci.image.manifest.v1+json` mediatype structure when marshalled to JSON.\npublic struct Manifest: Codable, Sendable {\n /// `schemaVersion` is the image manifest schema that this image follows.\n public let schemaVersion: Int\n\n /// `mediaType` specifies the type of this document data structure, e.g. `application/vnd.oci.image.manifest.v1+json`.\n public let mediaType: String?\n\n /// `config` references a configuration object for a container, by digest.\n /// The referenced configuration object is a JSON blob that the runtime uses to set up the container.\n public let config: Descriptor\n\n /// `layers` is an indexed list of layers referenced by the manifest.\n public let layers: [Descriptor]\n\n /// `annotations` contains arbitrary metadata for the image manifest.\n public let annotations: [String: String]?\n\n public init(\n schemaVersion: Int = 2, mediaType: String = MediaTypes.imageManifest, config: Descriptor, layers: [Descriptor],\n annotations: [String: String]? = nil\n ) {\n self.schemaVersion = schemaVersion\n self.mediaType = mediaType\n self.config = config\n self.layers = layers\n self.annotations = annotations\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Index.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// Source: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/index.go\n\nimport Foundation\n\n/// Index references manifests for various platforms.\n/// This structure provides `application/vnd.oci.image.index.v1+json` mediatype when marshalled to JSON.\npublic struct Index: Codable, Sendable {\n /// schemaVersion is the image manifest schema that this image follows\n public let schemaVersion: Int\n\n /// mediaType specifies the type of this document data structure e.g. `application/vnd.oci.image.index.v1+json`\n public let mediaType: String\n\n /// manifests references platform specific manifests.\n public var manifests: [Descriptor]\n\n /// annotations contains arbitrary metadata for the image index.\n public var annotations: [String: String]?\n\n public init(\n schemaVersion: Int = 2, mediaType: String = MediaTypes.index, manifests: [Descriptor],\n annotations: [String: String]? = nil\n ) {\n self.schemaVersion = schemaVersion\n self.mediaType = mediaType\n self.manifests = manifests\n self.annotations = annotations\n }\n}\n"], ["/containerization/Sources/Containerization/SystemPlatform.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOCI\n\n/// `SystemPlatform` describes an operating system and architecture pair.\n/// This is primarily used to choose what kind of OCI image to pull from a\n/// registry.\npublic struct SystemPlatform: Sendable, Codable {\n public enum OS: String, CaseIterable, Sendable, Codable {\n case linux\n case darwin\n }\n public let os: OS\n\n public enum Architecture: String, CaseIterable, Sendable, Codable {\n case arm64\n case amd64\n }\n public let architecture: Architecture\n\n public func ociPlatform() -> ContainerizationOCI.Platform {\n ContainerizationOCI.Platform(arch: architecture.rawValue, os: os.rawValue)\n }\n\n public static var linuxArm: SystemPlatform { .init(os: .linux, architecture: .arm64) }\n public static var linuxAmd: SystemPlatform { .init(os: .linux, architecture: .amd64) }\n}\n"], ["/containerization/Sources/Containerization/VirtualMachineAgent.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\n/// A protocol for the agent running inside a virtual machine. If an operation isn't\n/// supported the implementation MUST return a ContainerizationError with a code of\n/// `.unsupported`.\npublic protocol VirtualMachineAgent: Sendable {\n /// Perform a platform specific standard setup\n /// of the runtime environment.\n func standardSetup() async throws\n /// Close any resources held by the agent.\n func close() async throws\n\n // POSIX\n func getenv(key: String) async throws -> String\n func setenv(key: String, value: String) async throws\n func mount(_ mount: ContainerizationOCI.Mount) async throws\n func umount(path: String, flags: Int32) async throws\n func mkdir(path: String, all: Bool, perms: UInt32) async throws\n @discardableResult\n func kill(pid: Int32, signal: Int32) async throws -> Int32\n\n // Process lifecycle\n func createProcess(\n id: String,\n containerID: String?,\n stdinPort: UInt32?,\n stdoutPort: UInt32?,\n stderrPort: UInt32?,\n configuration: ContainerizationOCI.Spec,\n options: Data?\n ) async throws\n func startProcess(id: String, containerID: String?) async throws -> Int32\n func signalProcess(id: String, containerID: String?, signal: Int32) async throws\n func resizeProcess(id: String, containerID: String?, columns: UInt32, rows: UInt32) async throws\n func waitProcess(id: String, containerID: String?, timeoutInSeconds: Int64?) async throws -> Int32\n func deleteProcess(id: String, containerID: String?) async throws\n func closeProcessStdin(id: String, containerID: String?) async throws\n\n // Networking\n func up(name: String, mtu: UInt32?) async throws\n func down(name: String) async throws\n func addressAdd(name: String, address: String) async throws\n func routeAddDefault(name: String, gateway: String) async throws\n func configureDNS(config: DNS, location: String) async throws\n func configureHosts(config: Hosts, location: String) async throws\n}\n\nextension VirtualMachineAgent {\n public func closeProcessStdin(id: String, containerID: String?) async throws {\n throw ContainerizationError(.unsupported, message: \"closeProcessStdin\")\n }\n\n public func configureHosts(config: Hosts, location: String) async throws {\n throw ContainerizationError(.unsupported, message: \"configureHosts\")\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Syscall.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if canImport(Musl)\nimport Musl\n#elseif canImport(Glibc)\nimport Glibc\n#elseif canImport(Darwin)\nimport Darwin\n#else\n#error(\"retryingSyscall not supported on this platform.\")\n#endif\n\n/// Helper type to deal with running system calls.\npublic struct Syscall {\n /// Retry a syscall on EINTR.\n public static func retrying(_ closure: () -> T) -> T {\n while true {\n let res = closure()\n if res == -1 && errno == EINTR {\n continue\n }\n return res\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/FileManager+Temporary.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension FileManager {\n /// Returns a unique temporary directory to use.\n public func uniqueTemporaryDirectory(create: Bool = true) -> URL {\n let tempDirectoryURL = temporaryDirectory\n let uniqueDirectoryURL = tempDirectoryURL.appendingPathComponent(UUID().uuidString)\n if create {\n try? createDirectory(at: uniqueDirectoryURL, withIntermediateDirectories: true, attributes: nil)\n }\n return uniqueDirectoryURL\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/TempDir.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport Foundation\n\ninternal func createTemporaryDirectory(baseName: String) -> URL? {\n let url = FileManager.default.uniqueTemporaryDirectory().appendingPathComponent(\n \"\\(baseName).XXXXXX\")\n guard let templatePathData = (url.absoluteURL.path as NSString).utf8String else {\n return nil\n }\n\n let pathData = UnsafeMutablePointer(mutating: templatePathData)\n mkdtemp(pathData)\n\n return URL(fileURLWithPath: String(cString: pathData), isDirectory: true)\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/Authentication.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Abstraction for returning a token needed for logging into an OCI compliant registry.\npublic protocol Authentication: Sendable {\n func token() async throws -> String\n}\n\n/// Type representing authentication information for client to access the registry.\npublic struct BasicAuthentication: Authentication {\n /// The username for the authentication.\n let username: String\n /// The password or identity token for the user.\n let password: String\n\n public init(username: String, password: String) {\n self.username = username\n self.password = password\n }\n\n /// Get a token using the provided username and password. This will be a\n /// base64 encoded string of the username and password delimited by a colon.\n public func token() async throws -> String {\n let credentials = \"\\(username):\\(password)\"\n if let authenticationData = credentials.data(using: .utf8)?.base64EncodedString() {\n return \"Basic \\(authenticationData)\"\n }\n throw Error.invalidCredentials\n }\n\n /// `BasicAuthentication` errors.\n public enum Error: Swift.Error {\n case invalidCredentials\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension EXT4.InodeFlag {\n public static func | (lhs: Self, rhs: Self) -> Self {\n Self(rawValue: lhs.rawValue | rhs.rawValue)\n }\n\n public static func | (lhs: Self, rhs: Self) -> UInt32 {\n lhs.rawValue | rhs.rawValue\n }\n\n public static func | (lhs: Self, rhs: UInt32) -> UInt32 {\n lhs.rawValue | rhs\n }\n}\n\nextension EXT4.CompatFeature {\n public static func | (lhs: Self, rhs: Self) -> Self {\n EXT4.CompatFeature(rawValue: lhs.rawValue | rhs.rawValue)\n }\n\n public static func | (lhs: Self, rhs: Self) -> UInt32 {\n lhs.rawValue | rhs.rawValue\n }\n}\n\nextension EXT4.IncompatFeature {\n public static func | (lhs: Self, rhs: Self) -> Self {\n EXT4.IncompatFeature(rawValue: lhs.rawValue | rhs.rawValue)\n }\n\n public static func | (lhs: Self, rhs: Self) -> UInt32 {\n lhs.rawValue | rhs.rawValue\n }\n}\n\nextension EXT4.RoCompatFeature {\n public static func | (lhs: Self, rhs: Self) -> Self {\n EXT4.RoCompatFeature(rawValue: lhs.rawValue | rhs.rawValue)\n }\n\n public static func | (lhs: Self, rhs: Self) -> UInt32 {\n lhs.rawValue | rhs.rawValue\n }\n}\n\nextension EXT4.FileModeFlag {\n public static func | (lhs: Self, rhs: Self) -> Self {\n Self(rawValue: lhs.rawValue | rhs.rawValue)\n }\n\n public static func | (lhs: Self, rhs: Self) -> UInt16 {\n lhs.rawValue | rhs.rawValue\n }\n}\n\nextension EXT4.XAttrEntry {\n init(using bytes: [UInt8]) throws {\n guard bytes.count == 16 else {\n throw EXT4.Error.invalidXattrEntry\n }\n nameLength = bytes[0]\n nameIndex = bytes[1]\n let rawValue = Array(bytes[2...3])\n valueOffset = UInt16(littleEndian: rawValue.withUnsafeBytes { $0.load(as: UInt16.self) })\n\n let rawValueInum = Array(bytes[4...7])\n valueInum = UInt32(littleEndian: rawValueInum.withUnsafeBytes { $0.load(as: UInt32.self) })\n\n let rawSize = Array(bytes[8...11])\n valueSize = UInt32(littleEndian: rawSize.withUnsafeBytes { $0.load(as: UInt32.self) })\n\n let rawHash = Array(bytes[12...])\n hash = UInt32(littleEndian: rawHash.withUnsafeBytes { $0.load(as: UInt32.self) })\n }\n}\n\nextension EXT4 {\n static func tupleToArray(_ tuple: T) -> [UInt8] {\n let reflection = Mirror(reflecting: tuple)\n return reflection.children.compactMap { $0.value as? UInt8 }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Descriptor.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// Source: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/descriptor.go\n\nimport Foundation\n\n/// Descriptor describes the disposition of targeted content.\n/// This structure provides `application/vnd.oci.descriptor.v1+json` mediatype\n/// when marshalled to JSON.\npublic struct Descriptor: Codable, Sendable, Equatable {\n /// mediaType is the media type of the object this schema refers to.\n public let mediaType: String\n\n /// digest is the digest of the targeted content.\n public let digest: String\n\n /// size specifies the size in bytes of the blob.\n public let size: Int64\n\n /// urls specifies a list of URLs from which this object MAY be downloaded.\n public let urls: [String]?\n\n /// annotations contains arbitrary metadata relating to the targeted content.\n public var annotations: [String: String]?\n\n /// platform describes the platform which the image in the manifest runs on.\n ///\n /// This should only be used when referring to a manifest.\n public var platform: Platform?\n\n public init(\n mediaType: String, digest: String, size: Int64, urls: [String]? = nil, annotations: [String: String]? = nil,\n platform: Platform? = nil\n ) {\n self.mediaType = mediaType\n self.digest = digest\n self.size = size\n self.urls = urls\n self.annotations = annotations\n self.platform = platform\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/BinaryInteger+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension BinaryInteger {\n private func toUnsignedMemoryAmount(_ amount: UInt64) -> UInt64 {\n guard self > 0 else {\n fatalError(\"encountered negative number during conversion to memory amount\")\n }\n let val = UInt64(self)\n let (newVal, overflow) = val.multipliedReportingOverflow(by: amount)\n guard !overflow else {\n fatalError(\"UInt64 overflow when converting to memory amount\")\n }\n return newVal\n }\n\n public func kib() -> UInt64 {\n self.toUnsignedMemoryAmount(1 << 10)\n }\n\n public func mib() -> UInt64 {\n self.toUnsignedMemoryAmount(1 << 20)\n }\n\n public func gib() -> UInt64 {\n self.toUnsignedMemoryAmount(1 << 30)\n }\n\n public func tib() -> UInt64 {\n self.toUnsignedMemoryAmount(1 << 40)\n }\n\n public func pib() -> UInt64 {\n self.toUnsignedMemoryAmount(1 << 50)\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Sysctl.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Helper type to deal with system control functionalities.\npublic struct Sysctl {\n #if os(macOS)\n /// Simple `sysctlbyname` wrapper.\n public static func byName(_ name: String) throws -> Int64 {\n var num: Int64 = 0\n var size = MemoryLayout.size\n if sysctlbyname(name, &num, &size, nil, 0) != 0 {\n throw POSIXError.fromErrno()\n }\n return num\n }\n #endif\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/URL+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension URL {\n /// Returns the unescaped absolutePath of a URL joined by separator.\n public func absolutePath() -> String {\n #if os(macOS)\n return self.path(percentEncoded: false)\n #else\n return self.path\n #endif\n }\n\n /// Returns the domain name of a registry.\n public var domain: String? {\n guard let host = self.absoluteString.split(separator: \":\").first else {\n return nil\n }\n return String(host)\n }\n}\n"], ["/containerization/Sources/Containerization/DNSConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// DNS configuration for a container. The values will be used to\n/// construct /etc/resolv.conf for a given container.\npublic struct DNS: Sendable {\n /// The set of default nameservers to use if none are provided\n /// in the constructor.\n public static let defaultNameservers = [\"1.1.1.1\"]\n\n /// The nameservers a container should use.\n public var nameservers: [String]\n /// The DNS domain to use.\n public var domain: String?\n /// The DNS search domains to use.\n public var searchDomains: [String]\n /// The DNS options to use.\n public var options: [String]\n\n public init(\n nameservers: [String] = defaultNameservers,\n domain: String? = nil,\n searchDomains: [String] = [],\n options: [String] = []\n ) {\n self.nameservers = nameservers\n self.domain = domain\n self.searchDomains = searchDomains\n self.options = options\n }\n}\n\nextension DNS {\n public var resolvConf: String {\n var text = \"\"\n\n if !nameservers.isEmpty {\n text += nameservers.map { \"nameserver \\($0)\" }.joined(separator: \"\\n\") + \"\\n\"\n }\n\n if let domain {\n text += \"domain \\(domain)\\n\"\n }\n\n if !searchDomains.isEmpty {\n text += \"search \\(searchDomains.joined(separator: \" \"))\\n\"\n }\n\n if !options.isEmpty {\n text += \"opts \\(options.joined(separator: \" \"))\\n\"\n }\n\n return text\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/Content.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport Crypto\nimport Foundation\nimport NIOCore\n\n/// Protocol for defining a single OCI content\npublic protocol Content: Sendable {\n /// URL to the content\n var path: URL { get }\n\n /// sha256 of content\n func digest() throws -> SHA256.Digest\n\n /// Size of content\n func size() throws -> UInt64\n\n /// Data representation of entire content\n func data() throws -> Data\n\n /// Data representation partial content\n func data(offset: UInt64, length: Int) throws -> Data?\n\n /// Decode the content into an object\n func decode() throws -> T where T: Decodable\n}\n\n/// Protocol defining methods to fetch and push OCI content\npublic protocol ContentClient: Sendable {\n func fetch(name: String, descriptor: Descriptor) async throws -> T\n\n func fetchBlob(name: String, descriptor: Descriptor, into file: URL, progress: ProgressHandler?) async throws -> (Int64, SHA256Digest)\n\n func fetchData(name: String, descriptor: Descriptor) async throws -> Data\n\n func push(\n name: String,\n ref: String,\n descriptor: Descriptor,\n streamGenerator: () throws -> T,\n progress: ProgressHandler?\n ) async throws where T.Element == ByteBuffer\n\n}\n"], ["/containerization/Sources/Containerization/VirtualMachineAgent+Additions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Protocol to conform to if your agent is capable of relaying unix domain socket\n/// connections.\npublic protocol SocketRelayAgent {\n func relaySocket(port: UInt32, configuration: UnixSocketConfiguration) async throws\n func stopSocketRelay(configuration: UnixSocketConfiguration) async throws\n}\n"], ["/containerization/vminitd/Sources/vminitd/IOCloser+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\n\nextension Socket: IOCloser {}\n\nextension Terminal: IOCloser {\n var fileDescriptor: Int32 {\n self.handle.fileDescriptor\n }\n}\n\nextension FileHandle: IOCloser {}\n"], ["/containerization/Sources/ContainerizationOCI/Content/AsyncTypes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npackage actor AsyncStore {\n private var _value: T?\n\n package init(_ value: T? = nil) {\n self._value = value\n }\n\n package func get() -> T? {\n self._value\n }\n\n package func set(_ value: T) {\n self._value = value\n }\n}\n\npackage actor AsyncSet {\n private var buffer: Set\n\n package init(_ elements: S) where S.Element == T {\n buffer = Set(elements)\n }\n\n package var count: Int {\n buffer.count\n }\n\n package func insert(_ element: T) {\n buffer.insert(element)\n }\n\n @discardableResult\n package func remove(_ element: T) -> T? {\n buffer.remove(element)\n }\n\n package func contains(_ element: T) -> Bool {\n buffer.contains(element)\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/ContentStoreProtocol.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Crypto\nimport Foundation\n\n/// Protocol for defining a content store where OCI image metadata and layers will be managed\n/// and manipulated.\npublic protocol ContentStore: Sendable {\n /// Retrieves a piece of Content based on the digest string.\n /// Returns `nil` if the requested digest is not found.\n func get(digest: String) async throws -> Content?\n\n /// Retrieves a specific content metadata type based on the digest string.\n /// Returns `nil` if the requested digest is not found.\n func get(digest: String) async throws -> T?\n\n /// Remove a list of digests in the content store.\n @discardableResult\n func delete(digests: [String]) async throws -> ([String], UInt64)\n\n /// Removes all content from the store except for the digests in the provided list.\n @discardableResult\n func delete(keeping: [String]) async throws -> ([String], UInt64)\n\n /// Creates a transactional write to the content store.\n /// The function takes a closure given a temporary `URL` of the base directory which all contents should be written to.\n /// This is transaction write where any failed operation in the closure (caught exception) will result in all contents written\n /// in the closure to be deleted.\n ///\n /// If the closure succeeds, then all the content that have been written to the temporary `URL` will be moved into the actual\n /// blobs path of the content store.\n @discardableResult\n func ingest(_ body: @Sendable @escaping (URL) async throws -> Void) async throws -> [String]\n\n /// Creates a new ingest session and returns the session ID and temporary ingest directory corresponding to the session.\n /// The contents from the ingest directory are processed and moved into the content store once the session is marked complete.\n /// This can be done by invoking the `completeIngestSession` method with the returned session ID.\n func newIngestSession() async throws -> (id: String, ingestDir: URL)\n\n /// Completes a previously started ingest session corresponding to `id`.\n /// The contents from the ingest directory from the session are moved into the content store atomically.\n /// Any failure encountered will result in a transaction failure causing none of the contents to be ingested into the store.\n @discardableResult\n func completeIngestSession(_ id: String) async throws -> [String]\n\n /// Cancels a previously started ingest session corresponding to `id`.\n /// The contents from the ingest directory corresponding to the session are removed.\n func cancelIngestSession(_ id: String) async throws\n}\n"], ["/containerization/Sources/ContainerizationEXT4/FileTimestamps.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct FileTimestamps {\n public var access: Date\n public var modification: Date\n public var creation: Date\n public var now: Date\n\n public var accessLo: UInt32 {\n access.fs().lo\n }\n\n public var accessHi: UInt32 {\n access.fs().hi\n }\n\n public var modificationLo: UInt32 {\n modification.fs().lo\n }\n\n public var modificationHi: UInt32 {\n modification.fs().hi\n }\n\n public var creationLo: UInt32 {\n creation.fs().lo\n }\n\n public var creationHi: UInt32 {\n creation.fs().hi\n }\n\n public var nowLo: UInt32 {\n now.fs().lo\n }\n\n public var nowHi: UInt32 {\n now.fs().hi\n }\n\n public init(access: Date?, modification: Date?, creation: Date?) {\n now = Date()\n self.access = access ?? now\n self.modification = modification ?? now\n self.creation = creation ?? now\n }\n\n public init() {\n self.init(access: nil, modification: nil, creation: nil)\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/String+Extension.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension String {\n /// Removes any prefix (sha256:) from a digest string.\n public var trimmingDigestPrefix: String {\n let split = self.split(separator: \":\")\n if split.count == 2 {\n return String(split[1])\n }\n return self\n }\n}\n"], ["/containerization/Sources/Containerization/Hash.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\n\nimport Crypto\nimport ContainerizationError\n\nfunc hashMountSource(source: String) throws -> String {\n guard let data = source.data(using: .utf8) else {\n throw ContainerizationError(.invalidArgument, message: \"\\(source) could not be converted to Data\")\n }\n return String(SHA256.hash(data: data).encoded.prefix(36))\n}\n\n#endif\n"], ["/containerization/Sources/ContainerizationOS/POSIXError+Helpers.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension POSIXError {\n public static func fromErrno() -> POSIXError {\n guard let errCode = POSIXErrorCode(rawValue: errno) else {\n fatalError(\"failed to convert errno to POSIXErrorCode\")\n }\n return POSIXError(errCode)\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/ProgressEvent.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A progress update event.\npublic struct ProgressEvent: Sendable {\n /// The event name. The possible values:\n /// - `add-items`: Increment the number of processed items by `value`.\n /// - `add-total-items`: Increment the total number of items to process by `value`.\n /// - `add-size`: Increment the size of processed items by `value`.\n /// - `add-total-size`: Increment the total size of items to process by `value`.\n public let event: String\n /// The event value.\n public let value: any Sendable\n\n /// Creates an instance.\n /// - Parameters:\n /// - event: The event name.\n /// - value: The event value.\n public init(event: String, value: any Sendable) {\n self.event = event\n self.value = value\n }\n}\n\n/// The progress update handler.\npublic typealias ProgressHandler = @Sendable (_ events: [ProgressEvent]) async -> Void\n"], ["/containerization/Sources/ContainerizationOCI/Version.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic struct RuntimeSpecVersion: Sendable {\n public let major, minor, patch: Int\n public let dev: String\n\n public static let current = RuntimeSpecVersion(\n major: 1,\n minor: 0,\n patch: 2,\n dev: \"-dev\"\n )\n\n public init(major: Int, minor: Int, patch: Int, dev: String) {\n self.major = major\n self.minor = minor\n self.patch = patch\n self.dev = dev\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/SHA256+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Crypto\nimport Foundation\n\nextension SHA256.Digest {\n /// Returns the digest as a string.\n public var digestString: String {\n let parts = self.description.split(separator: \": \")\n return \"sha256:\\(parts[1])\"\n }\n\n /// Returns the digest without a 'sha256:' prefix.\n public var encoded: String {\n let parts = self.description.split(separator: \": \")\n return String(parts[1])\n }\n}\n"], ["/containerization/Sources/Containerization/NATInterface.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic struct NATInterface: Interface {\n public var address: String\n public var gateway: String?\n public var macAddress: String?\n\n public init(address: String, gateway: String?, macAddress: String? = nil) {\n self.address = address\n self.gateway = gateway\n self.macAddress = macAddress\n }\n}\n"], ["/containerization/Sources/SendableProperty/SendableProperty.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// A declaration of the `@SendableProperty` macro.\n@attached(peer, names: arbitrary)\n@attached(accessor)\npublic macro SendableProperty() = #externalMacro(module: \"SendablePropertyMacros\", type: \"SendablePropertyMacro\")\n"], ["/containerization/Sources/SendableProperty/SendablePropertyUnchecked.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// A declaration of the `@SendablePropertyUnchecked` macro.\n@attached(peer, names: arbitrary)\n@attached(accessor)\npublic macro SendablePropertyUnchecked() = #externalMacro(module: \"SendablePropertyMacros\", type: \"SendablePropertyMacroUnchecked\")\n"], ["/containerization/vminitd/Sources/vminitd/IOCloser.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nprotocol IOCloser: Sendable {\n var fileDescriptor: Int32 { get }\n\n func close() throws\n}\n"], ["/containerization/Sources/Containerization/Image/Unpacker/Unpacker.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\n/// The `Unpacker` protocol defines a standardized interface that involves\n/// decompressing, extracting image layers and preparing it for use.\n///\n/// The `Unpacker` is responsible for managing the lifecycle of the\n/// unpacking process, including any temporary files or resources, until the\n/// `Mount` object is produced.\npublic protocol Unpacker {\n\n /// Unpacks the provided image to a specified path for a given platform.\n ///\n /// This asynchronous method should handle the entire unpacking process, from reading\n /// the `Image` layers for the given `Platform` via its `Manifest`,\n /// to making the extracted contents available as a `Mount`.\n /// Implementations of this method may apply platform-specific optimizations\n /// or transformations during the unpacking.\n ///\n /// Progress updates can be observed via the optional `progress` handler.\n func unpack(_ image: Image, for platform: Platform, at path: URL, progress: ProgressHandler?) async throws -> Mount\n\n}\n"], ["/containerization/Sources/SendablePropertyMacros/SendablePropertyPlugin.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport SwiftCompilerPlugin\nimport SwiftSyntaxMacros\n\n/// A plugin that registers the `SendablePropertyMacroUnchecked` and `SendablePropertyMacro`.\n@main\nstruct SendablePropertyPlugin: CompilerPlugin {\n let providingMacros: [Macro.Type] = [\n SendablePropertyMacroUnchecked.self,\n SendablePropertyMacro.self,\n ]\n}\n"], ["/containerization/Sources/ContainerizationOCI/MediaType.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// MediaTypes represent all supported OCI image content types for both metadata and layer formats.\n/// Follows all distributable media types in: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/mediatype.go\npublic struct MediaTypes: Codable, Sendable {\n /// Specifies the media type for a content descriptor.\n public static let descriptor = \"application/vnd.oci.descriptor.v1+json\"\n\n /// Specifies the media type for the oci-layout.\n public static let layoutHeader = \"application/vnd.oci.layout.header.v1+json\"\n\n /// Specifies the media type for an image index.\n public static let index = \"application/vnd.oci.image.index.v1+json\"\n\n /// Specifies the media type for an image manifest.\n public static let imageManifest = \"application/vnd.oci.image.manifest.v1+json\"\n\n /// Specifies the media type for the image configuration.\n public static let imageConfig = \"application/vnd.oci.image.config.v1+json\"\n\n /// Specifies the media type for an unused blob containing the value \"{}\".\n public static let emptyJSON = \"application/vnd.oci.empty.v1+json\"\n\n /// Specifies the media type for a Docker image manifest.\n public static let dockerManifest = \"application/vnd.docker.distribution.manifest.v2+json\"\n\n /// Specifies the media type for a Docker image manifest list.\n public static let dockerManifestList = \"application/vnd.docker.distribution.manifest.list.v2+json\"\n\n /// The Docker media type used for image configurations.\n public static let dockerImageConfig = \"application/vnd.docker.container.image.v1+json\"\n\n /// The media type used for layers referenced by the manifest.\n public static let imageLayer = \"application/vnd.oci.image.layer.v1.tar\"\n\n /// The media type used for gzipped layers referenced by the manifest.\n public static let imageLayerGzip = \"application/vnd.oci.image.layer.v1.tar+gzip\"\n\n /// The media type used for zstd compressed layers referenced by the manifest.\n public static let imageLayerZstd = \"application/vnd.oci.image.layer.v1.tar+zstd\"\n\n /// The Docker media type used for uncompressed layers referenced by an image manifest.\n public static let dockerImageLayer = \"application/vnd.docker.image.rootfs.diff.tar\"\n\n /// The Docker media type used for gzipped layers referenced by an image manifest.\n public static let dockerImageLayerGzip = \"application/vnd.docker.image.rootfs.diff.tar.gzip\"\n\n /// The Docker media type used for zstd compressed layers referenced by an image manifest.\n public static let dockerImageLayerZstd = \"application/vnd.docker.image.rootfs.diff.tar.zstd\"\n\n /// The media type used for in-toto attestations blobs.\n public static let inTotoAttestationBlob = \"application/vnd.in-toto+json\"\n}\n"], ["/containerization/Sources/Containerization/IO/ReaderStream.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A type that returns a stream of Data.\npublic protocol ReaderStream: Sendable {\n func stream() -> AsyncStream\n}\n"], ["/containerization/Sources/Containerization/Container.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// The core protocol container implementations must implement.\npublic protocol Container {\n /// ID for the container.\n var id: String { get }\n /// The amount of cpus assigned to the container.\n var cpus: Int { get }\n /// The memory in bytes assigned to the container.\n var memoryInBytes: UInt64 { get }\n /// The network interfaces assigned to the container.\n var interfaces: [any Interface] { get }\n}\n"], ["/containerization/Sources/Containerization/Interface.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A network interface.\npublic protocol Interface: Sendable {\n /// The interface IPv4 address and subnet prefix length, as a CIDR address.\n /// Example: `192.168.64.3/24`\n var address: String { get }\n\n /// The IP address for the default route, or nil for no default route.\n var gateway: String? { get }\n\n /// The interface MAC address, or nil to auto-configure the address.\n var macAddress: String? { get }\n}\n"], ["/containerization/vminitd/Sources/vminitd/HostStdio.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nstruct HostStdio: Sendable {\n let stdin: UInt32?\n let stdout: UInt32?\n let stderr: UInt32?\n let terminal: Bool\n}\n"], ["/containerization/Sources/Containerization/IO/Writer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A type that writes the provided Data.\npublic protocol Writer: Sendable {\n func write(_ data: Data) throws\n}\n"], ["/containerization/Sources/ContainerizationOCI/AnnotationKeys.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// AnnotationKeys contains a subset of \"dictionary keys\" for commonly used annotations in an OCI Image Descriptor\n/// https://github.com/opencontainers/image-spec/blob/main/annotations.md\npublic struct AnnotationKeys: Codable, Sendable {\n public static let containerizationIndexIndirect = \"com.apple.containerization.index.indirect\"\n public static let containerizationImageName = \"com.apple.containerization.image.name\"\n public static let containerdImageName = \"io.containerd.image.name\"\n public static let openContainersImageName = \"org.opencontainers.image.ref.name\"\n}\n"], ["/containerization/Sources/Containerization/VirtualMachineManager.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A protocol to implement for virtual machine isolated containers.\npublic protocol VirtualMachineManager: Sendable {\n func create(container: Container) throws -> any VirtualMachineInstance\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 03:23:08", "created_task_model": "DeepSeek-R1", "function_skeleton": "private func handleConn ( conn: ContainerizationOS.Socket , connType: SocketType ) async throws { }", "code_description": "This code segment functions to: Relay data between two network connections by monitoring read/write events and transferring data bidirectionally while handling connection lifecycle events and error conditions through asynchronous I/O operations."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```swift\n[TASK_BEGIN]\n private func handleConn(conn: Socket, connType: SocketType) async throws {\n let targetType: any SocketTypeProtocol\n switch connType {\n case .unix:\n // Connect to VSOCK on host CID with configured port\n targetType = VsockType(port: self.port, cid: VsockType.hostCID)\n case .vsock:\n // Connect to UNIX socket at configured path\n targetType = try UnixType(\n path: self.path.path,\n perms: self.udsPerms,\n unlinkExisting: false\n )\n }\n \n let targetConn = try Socket(type: targetType)\n try await targetConn.connect()\n \n // Bidirectional data proxying\n try await withThrowingTaskGroup(of: Void.self) { group in\n group.addTask {\n try await conn.copy(to: targetConn)\n }\n group.addTask {\n try await targetConn.copy(to: conn)\n }\n try await group.waitForAll()\n }\n }\n[TASK_END]\n```", "inference_time": "2025-08-21 03-24-05"}, "editdistance_info": {"edit_distance": 12.6697, "calculate_time": "2025-08-21 03:24:05", "true_code_clean": "private func handleConn(\n conn: ContainerizationOS.Socket,\n connType: SocketType\n ) async throws {\n try await withCheckedThrowingContinuation { (c: CheckedContinuation) in\n do {\n nonisolated(unsafe) var relayTo: ContainerizationOS.Socket\n switch connType {\n case .unix:\n let type = VsockType(\n port: self.port,\n cid: VsockType.hostCID\n )\n relayTo = try Socket(\n type: type,\n closeOnDeinit: false\n )\n case .vsock:\n let type = try UnixType(path: self.path.path)\n relayTo = try Socket(\n type: type,\n closeOnDeinit: false\n )\n }\n try relayTo.connect()\n nonisolated(unsafe) var clientFile = OSFile.SpliceFile(fd: conn.fileDescriptor)\n nonisolated(unsafe) var serverFile = OSFile.SpliceFile(fd: relayTo.fileDescriptor)\n let cleanup = { @Sendable in\n do {\n try ProcessSupervisor.default.poller.delete(clientFile.fileDescriptor)\n try ProcessSupervisor.default.poller.delete(serverFile.fileDescriptor)\n try conn.close()\n try relayTo.close()\n } catch {\n self.log?.error(\"Failed to clean up vsock proxy: \\(error)\")\n }\n c.resume()\n }\n try! ProcessSupervisor.default.poller.add(clientFile.fileDescriptor, mask: EPOLLIN | EPOLLOUT) { mask in\n if mask.readyToRead {\n do {\n let (_, _, action) = try OSFile.splice(from: &clientFile, to: &serverFile)\n if action == .eof || action == .brokenPipe {\n return cleanup()\n }\n } catch {\n return cleanup()\n }\n }\n if mask.readyToWrite {\n do {\n let (_, _, action) = try OSFile.splice(from: &serverFile, to: &clientFile)\n if action == .eof || action == .brokenPipe {\n return cleanup()\n }\n } catch {\n return cleanup()\n }\n }\n if mask.isHangup {\n return cleanup()\n }\n }\n try! ProcessSupervisor.default.poller.add(serverFile.fileDescriptor, mask: EPOLLIN | EPOLLOUT) { mask in\n if mask.readyToRead {\n do {\n let (_, _, action) = try OSFile.splice(from: &serverFile, to: &clientFile)\n if action == .eof || action == .brokenPipe {\n return cleanup()\n }\n } catch {\n return cleanup()\n }\n }\n if mask.readyToWrite {\n do {\n let (_, _, action) = try OSFile.splice(from: &clientFile, to: &serverFile)\n if action == .eof || action == .brokenPipe {\n return cleanup()\n }\n } catch {\n return cleanup()\n }\n }\n if mask.isHangup {\n return cleanup()\n }\n }\n } catch {\n c.resume(throwing: error)\n }\n }\n }", "predict_code_clean": "private func handleConn(conn: Socket, connType: SocketType) async throws {\n let targetType: any SocketTypeProtocol\n switch connType {\n case .unix:\n targetType = VsockType(port: self.port, cid: VsockType.hostCID)\n case .vsock:\n targetType = try UnixType(\n path: self.path.path,\n perms: self.udsPerms,\n unlinkExisting: false\n )\n }\n let targetConn = try Socket(type: targetType)\n try await targetConn.connect()\n try await withThrowingTaskGroup(of: Void.self) { group in\n group.addTask {\n try await conn.copy(to: targetConn)\n }\n group.addTask {\n try await targetConn.copy(to: conn)\n }\n try await group.waitForAll()\n }\n }"}} +{"repo_name": "containerization", "file_name": "/containerization/Sources/Containerization/NATNetworkInterface.swift", "inference_info": {"prefix_code": "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\n\nimport vmnet\nimport Virtualization\nimport ContainerizationError\nimport Foundation\nimport Synchronization\n\n/// An interface that uses NAT to provide an IP address for a given\n/// container/virtual machine.\n@available(macOS 26, *)\npublic final class NATNetworkInterface: Interface, Sendable {\n public var address: String {\n get {\n state.withLock { $0.address }\n }\n set {\n state.withLock { $0.address = newValue }\n }\n\n }\n\n public var gateway: String? {\n get {\n state.withLock { $0.gateway }\n }\n set {\n state.withLock { $0.gateway = newValue }\n }\n }\n\n @available(macOS 26, *)\n public var reference: vmnet_network_ref {\n state.withLock { $0.reference }\n }\n\n public var macAddress: String? {\n get {\n state.withLock { $0.macAddress }\n }\n set {\n state.withLock { $0.macAddress = newValue }\n }\n }\n\n private struct State {\n var address: String\n var gateway: String?\n var reference: vmnet_network_ref!\n var macAddress: String?\n }\n\n private let state: Mutex\n\n @available(macOS 26, *)\n public init(\n address: String,\n gateway: String?,\n reference: sending vmnet_network_ref,\n macAddress: String? = nil\n ) {\n let state = State(\n address: address,\n gateway: gateway,\n reference: reference,\n macAddress: macAddress\n )\n self.state = Mutex(state)\n }\n\n ", "suffix_code": "\n}\n\n@available(macOS 26, *)\nextension NATNetworkInterface: VZInterface {\n public func device() throws -> VZVirtioNetworkDeviceConfiguration {\n let config = VZVirtioNetworkDeviceConfiguration()\n if let macAddress = self.macAddress {\n guard let mac = VZMACAddress(string: macAddress) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid mac address \\(macAddress)\")\n }\n config.macAddress = mac\n }\n\n config.attachment = VZVmnetNetworkDeviceAttachment(network: self.reference)\n return config\n }\n}\n\n#endif\n", "middle_code": "@available(macOS, obsoleted: 26, message: \"Use init(address:gateway:reference:macAddress:) instead\")\n public init(\n address: String,\n gateway: String?,\n macAddress: String? = nil\n ) {\n let state = State(\n address: address,\n gateway: gateway,\n reference: nil,\n macAddress: macAddress\n )\n self.state = Mutex(state)\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "swift", "sub_task_type": null}, "context_code": [["/containerization/Sources/Containerization/ContainerManager.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport ContainerizationExtras\nimport Virtualization\nimport vmnet\n\n/// A manager for creating and running containers.\n/// Supports container networking options.\npublic struct ContainerManager: Sendable {\n public let imageStore: ImageStore\n private let vmm: VirtualMachineManager\n private let network: Network?\n\n private var containerRoot: URL {\n self.imageStore.path.appendingPathComponent(\"containers\")\n }\n\n /// A network that can allocate and release interfaces for use with containers.\n public protocol Network: Sendable {\n func create(_ id: String) throws -> Interface?\n func release(_ id: String) throws\n }\n\n /// A network backed by vmnet on macOS.\n @available(macOS 26.0, *)\n public struct VmnetNetwork: Network {\n private let allocator: Allocator\n nonisolated(unsafe) private let reference: vmnet_network_ref\n\n /// The IPv4 subnet of this network.\n public let subnet: CIDRAddress\n\n /// The gateway address of this network.\n public var gateway: IPv4Address {\n subnet.gateway\n }\n\n struct Allocator: Sendable {\n private let addressAllocator: any AddressAllocator\n private let cidr: CIDRAddress\n private var allocations: [String: UInt32]\n\n init(cidr: CIDRAddress) throws {\n self.cidr = cidr\n self.allocations = .init()\n let size = Int(cidr.upper.value - cidr.lower.value - 3)\n self.addressAllocator = try UInt32.rotatingAllocator(\n lower: cidr.lower.value + 2,\n size: UInt32(size)\n )\n }\n\n func allocate(_ id: String) throws -> String {\n if allocations[id] != nil {\n throw ContainerizationError(.exists, message: \"allocation with id \\(id) already exists\")\n }\n let index = try addressAllocator.allocate()\n let ip = IPv4Address(fromValue: index)\n return try CIDRAddress(ip, prefixLength: cidr.prefixLength).description\n }\n\n func release(_ id: String) throws {\n if let index = self.allocations[id] {\n try addressAllocator.release(index)\n }\n }\n }\n\n /// A network interface supporting the vmnet_network_ref.\n public struct Interface: Containerization.Interface, VZInterface, Sendable {\n public let address: String\n public let gateway: String?\n public let macAddress: String?\n\n nonisolated(unsafe) private let reference: vmnet_network_ref\n\n public init(\n reference: vmnet_network_ref,\n address: String,\n gateway: String,\n macAddress: String? = nil\n ) {\n self.address = address\n self.gateway = gateway\n self.macAddress = macAddress\n self.reference = reference\n }\n\n /// Returns the underlying `VZVirtioNetworkDeviceConfiguration`.\n public func device() throws -> VZVirtioNetworkDeviceConfiguration {\n let config = VZVirtioNetworkDeviceConfiguration()\n if let macAddress = self.macAddress {\n guard let mac = VZMACAddress(string: macAddress) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid mac address \\(macAddress)\")\n }\n config.macAddress = mac\n }\n config.attachment = VZVmnetNetworkDeviceAttachment(network: self.reference)\n return config\n }\n }\n\n /// Creates a new network.\n /// - Parameter subnet: The subnet to use for this network.\n public init(subnet: String? = nil) throws {\n var status: vmnet_return_t = .VMNET_FAILURE\n guard let config = vmnet_network_configuration_create(.VMNET_SHARED_MODE, &status) else {\n throw ContainerizationError(.unsupported, message: \"failed to create vmnet config with status \\(status)\")\n }\n\n vmnet_network_configuration_disable_dhcp(config)\n\n if let subnet {\n try Self.configureSubnet(config, subnet: try CIDRAddress(subnet))\n }\n\n guard let ref = vmnet_network_create(config, &status), status == .VMNET_SUCCESS else {\n throw ContainerizationError(.unsupported, message: \"failed to create vmnet network with status \\(status)\")\n }\n\n let cidr = try Self.getSubnet(ref)\n\n self.allocator = try .init(cidr: cidr)\n self.subnet = cidr\n self.reference = ref\n }\n\n /// Returns a new interface for use with a container.\n /// - Parameter id: The container ID.\n public func create(_ id: String) throws -> Containerization.Interface? {\n let address = try allocator.allocate(id)\n return Self.Interface(\n reference: self.reference,\n address: address,\n gateway: self.gateway.description,\n )\n }\n\n /// Performs cleanup of an interface.\n /// - Parameter id: The container ID.\n public func release(_ id: String) throws {\n try allocator.release(id)\n }\n\n private static func getSubnet(_ ref: vmnet_network_ref) throws -> CIDRAddress {\n var subnet = in_addr()\n var mask = in_addr()\n vmnet_network_get_ipv4_subnet(ref, &subnet, &mask)\n\n let sa = UInt32(bigEndian: subnet.s_addr)\n let mv = UInt32(bigEndian: mask.s_addr)\n\n let lower = IPv4Address(fromValue: sa & mv)\n let upper = IPv4Address(fromValue: lower.value + ~mv)\n\n return try CIDRAddress(lower: lower, upper: upper)\n }\n\n private static func configureSubnet(_ config: vmnet_network_configuration_ref, subnet: CIDRAddress) throws {\n let gateway = subnet.gateway\n\n var ga = in_addr()\n inet_pton(AF_INET, gateway.description, &ga)\n\n let mask = IPv4Address(fromValue: subnet.prefixLength.prefixMask32)\n var ma = in_addr()\n inet_pton(AF_INET, mask.description, &ma)\n\n guard vmnet_network_configuration_set_ipv4_subnet(config, &ga, &ma) == .VMNET_SUCCESS else {\n throw ContainerizationError(.internalError, message: \"failed to set subnet \\(subnet) for network\")\n }\n }\n }\n\n /// Create a new manager with the provided kernel and initfs mount.\n public init(\n kernel: Kernel,\n initfs: Mount,\n network: Network? = nil\n ) throws {\n self.imageStore = ImageStore.default\n self.network = network\n try Self.createRootDirectory(path: self.imageStore.path)\n self.vmm = VZVirtualMachineManager(\n kernel: kernel,\n initialFilesystem: initfs,\n bootlog: self.imageStore.path.appendingPathComponent(\"bootlog.log\").absolutePath()\n )\n }\n\n /// Create a new manager with the provided kernel and image reference for the initfs.\n public init(\n kernel: Kernel,\n initfsReference: String,\n network: Network? = nil\n ) async throws {\n self.imageStore = ImageStore.default\n self.network = network\n try Self.createRootDirectory(path: self.imageStore.path)\n\n let initPath = self.imageStore.path.appendingPathComponent(\"initfs.ext4\")\n let initImage = try await self.imageStore.getInitImage(reference: initfsReference)\n let initfs = try await {\n do {\n return try await initImage.initBlock(at: initPath, for: .linuxArm)\n } catch let err as ContainerizationError {\n guard err.code == .exists else {\n throw err\n }\n return .block(\n format: \"ext4\",\n source: initPath.absolutePath(),\n destination: \"/\",\n options: [\"ro\"]\n )\n }\n }()\n\n self.vmm = VZVirtualMachineManager(\n kernel: kernel,\n initialFilesystem: initfs,\n bootlog: self.imageStore.path.appendingPathComponent(\"bootlog.log\").absolutePath()\n )\n }\n\n /// Create a new manager with the provided vmm and network.\n public init(\n vmm: any VirtualMachineManager,\n network: Network? = nil\n ) throws {\n self.imageStore = ImageStore.default\n try Self.createRootDirectory(path: self.imageStore.path)\n self.network = network\n self.vmm = vmm\n }\n\n private static func createRootDirectory(path: URL) throws {\n try FileManager.default.createDirectory(\n at: path.appendingPathComponent(\"containers\"),\n withIntermediateDirectories: true\n )\n }\n\n /// Returns a new container from the provided image reference.\n /// - Parameters:\n /// - id: The container ID.\n /// - reference: The image reference.\n /// - rootfsSizeInBytes: The size of the root filesystem in bytes. Defaults to 8 GiB.\n public func create(\n _ id: String,\n reference: String,\n rootfsSizeInBytes: UInt64 = 8.gib(),\n configuration: (inout LinuxContainer.Configuration) throws -> Void\n ) async throws -> LinuxContainer {\n let image = try await imageStore.get(reference: reference, pull: true)\n return try await create(\n id,\n image: image,\n rootfsSizeInBytes: rootfsSizeInBytes,\n configuration: configuration\n )\n }\n\n /// Returns a new container from the provided image.\n /// - Parameters:\n /// - id: The container ID.\n /// - image: The image.\n /// - rootfsSizeInBytes: The size of the root filesystem in bytes. Defaults to 8 GiB.\n public func create(\n _ id: String,\n image: Image,\n rootfsSizeInBytes: UInt64 = 8.gib(),\n configuration: (inout LinuxContainer.Configuration) throws -> Void\n ) async throws -> LinuxContainer {\n let path = try createContainerRoot(id)\n\n let rootfs = try await unpack(\n image: image,\n destination: path.appendingPathComponent(\"rootfs.ext4\"),\n size: rootfsSizeInBytes\n )\n return try await create(\n id,\n image: image,\n rootfs: rootfs,\n configuration: configuration\n )\n }\n\n /// Returns a new container from the provided image and root filesystem mount.\n /// - Parameters:\n /// - id: The container ID.\n /// - image: The image.\n /// - rootfs: The root filesystem mount pointing to an existing block file.\n public func create(\n _ id: String,\n image: Image,\n rootfs: Mount,\n configuration: (inout LinuxContainer.Configuration) throws -> Void\n ) async throws -> LinuxContainer {\n let imageConfig = try await image.config(for: .current).config\n return try LinuxContainer(\n id,\n rootfs: rootfs,\n vmm: self.vmm\n ) { config in\n if let imageConfig {\n config.process = .init(from: imageConfig)\n }\n if let interface = try self.network?.create(id) {\n config.interfaces = [interface]\n config.dns = .init(nameservers: [interface.gateway!])\n }\n try configuration(&config)\n }\n }\n\n /// Returns an existing container from the provided image and root filesystem mount.\n /// - Parameters:\n /// - id: The container ID.\n /// - image: The image.\n public func get(\n _ id: String,\n image: Image,\n ) async throws -> LinuxContainer {\n let path = containerRoot.appendingPathComponent(id)\n guard FileManager.default.fileExists(atPath: path.absolutePath()) else {\n throw ContainerizationError(.notFound, message: \"\\(id) does not exist\")\n }\n\n let rootfs: Mount = .block(\n format: \"ext4\",\n source: path.appendingPathComponent(\"rootfs.ext4\").absolutePath(),\n destination: \"/\",\n options: []\n )\n\n let imageConfig = try await image.config(for: .current).config\n return try LinuxContainer(\n id,\n rootfs: rootfs,\n vmm: self.vmm\n ) { config in\n if let imageConfig {\n config.process = .init(from: imageConfig)\n }\n if let interface = try self.network?.create(id) {\n config.interfaces = [interface]\n config.dns = .init(nameservers: [interface.gateway!])\n }\n }\n }\n\n /// Performs the cleanup of a container.\n /// - Parameter id: The container ID.\n public func delete(_ id: String) throws {\n try self.network?.release(id)\n let path = containerRoot.appendingPathComponent(id)\n try FileManager.default.removeItem(at: path)\n }\n\n private func createContainerRoot(_ id: String) throws -> URL {\n let path = containerRoot.appendingPathComponent(id)\n try FileManager.default.createDirectory(at: path, withIntermediateDirectories: false)\n return path\n }\n\n private func unpack(image: Image, destination: URL, size: UInt64) async throws -> Mount {\n do {\n let unpacker = EXT4Unpacker(blockSizeInBytes: size)\n return try await unpacker.unpack(image, for: .current, at: destination)\n } catch let err as ContainerizationError {\n if err.code == .exists {\n return .block(\n format: \"ext4\",\n source: destination.absolutePath(),\n destination: \"/\",\n options: []\n )\n }\n throw err\n }\n }\n}\n\nextension CIDRAddress {\n /// The gateway address of the network.\n public var gateway: IPv4Address {\n IPv4Address(fromValue: self.lower.value + 1)\n }\n}\n\n@available(macOS 26.0, *)\nprivate struct SendableReference: Sendable {\n nonisolated(unsafe) private let reference: vmnet_network_ref\n}\n\n#endif\n"], ["/containerization/Sources/Containerization/VZVirtualMachineInstance.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Logging\nimport NIOCore\nimport NIOPosix\nimport Synchronization\nimport Virtualization\n\nstruct VZVirtualMachineInstance: VirtualMachineInstance, Sendable {\n typealias Agent = Vminitd\n\n /// Attached mounts on the sandbox.\n public let mounts: [AttachedFilesystem]\n\n /// Returns the runtime state of the vm.\n public var state: VirtualMachineInstanceState {\n vzStateToInstanceState()\n }\n\n /// The sandbox configuration.\n private let config: Configuration\n public struct Configuration: Sendable {\n /// Amount of cpus to allocated.\n public var cpus: Int\n /// Amount of memory in bytes allocated.\n public var memoryInBytes: UInt64\n /// Toggle rosetta's x86_64 emulation support.\n public var rosetta: Bool\n /// Toggle nested virtualization support.\n public var nestedVirtualization: Bool\n /// Mount attachments.\n public var mounts: [Mount]\n /// Network interface attachments.\n public var interfaces: [any Interface]\n /// Kernel image.\n public var kernel: Kernel?\n /// The root filesystem.\n public var initialFilesystem: Mount?\n /// File path to store the sandbox boot logs.\n public var bootlog: URL?\n\n init() {\n self.cpus = 4\n self.memoryInBytes = 1024.mib()\n self.rosetta = false\n self.nestedVirtualization = false\n self.mounts = []\n self.interfaces = []\n }\n }\n\n private nonisolated(unsafe) let vm: VZVirtualMachine\n private let queue: DispatchQueue\n private let group: MultiThreadedEventLoopGroup\n private let lock: AsyncLock\n private let timeSyncer: TimeSyncer\n private let logger: Logger?\n\n public init(\n group: MultiThreadedEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount),\n logger: Logger? = nil,\n with: (inout Configuration) throws -> Void\n ) throws {\n var config = Configuration()\n try with(&config)\n try self.init(group: group, config: config, logger: logger)\n }\n\n init(group: MultiThreadedEventLoopGroup, config: Configuration, logger: Logger?) throws {\n self.config = config\n self.group = group\n self.lock = .init()\n self.queue = DispatchQueue(label: \"com.apple.containerization.sandbox.\\(UUID().uuidString)\")\n self.mounts = try config.mountAttachments()\n self.logger = logger\n self.timeSyncer = .init(logger: logger)\n\n self.vm = VZVirtualMachine(\n configuration: try config.toVZ(),\n queue: self.queue\n )\n }\n}\n\nextension VZVirtualMachineInstance {\n func vzStateToInstanceState() -> VirtualMachineInstanceState {\n self.queue.sync {\n let state: VirtualMachineInstanceState\n switch self.vm.state {\n case .starting:\n state = .starting\n case .running:\n state = .running\n case .stopping:\n state = .stopping\n case .stopped:\n state = .stopped\n default:\n state = .unknown\n }\n return state\n }\n }\n\n func start() async throws {\n try await lock.withLock { _ in\n guard self.state == .stopped else {\n throw ContainerizationError(\n .invalidState,\n message: \"sandbox is not stopped \\(self.state)\"\n )\n }\n\n // Do any necessary setup needed prior to starting the guest.\n try await self.prestart()\n\n try await self.vm.start(queue: self.queue)\n\n let agent = Vminitd(\n connection: try await self.vm.waitForAgent(queue: self.queue),\n group: self.group\n )\n\n do {\n if self.config.rosetta {\n try await agent.enableRosetta()\n }\n } catch {\n try await agent.close()\n throw error\n }\n\n // Don't close our remote context as we are providing\n // it to our time sync routine.\n await self.timeSyncer.start(context: agent)\n }\n }\n\n func stop() async throws {\n try await lock.withLock { _ in\n // NOTE: We should record HOW the vm stopped eventually. If the vm exited\n // unexpectedly virtualization framework offers you a way to store\n // an error on how it exited. We should report that here instead of the\n // generic vm is not running.\n guard self.state == .running else {\n throw ContainerizationError(.invalidState, message: \"vm is not running\")\n }\n\n try await self.timeSyncer.close()\n\n try await self.vm.stop(queue: self.queue)\n try await self.group.shutdownGracefully()\n }\n }\n\n public func dialAgent() async throws -> Vminitd {\n let conn = try await dial(Vminitd.port)\n return Vminitd(connection: conn, group: self.group)\n }\n}\n\nextension VZVirtualMachineInstance {\n func dial(_ port: UInt32) async throws -> FileHandle {\n try await vm.connect(\n queue: queue,\n port: port\n ).dupHandle()\n }\n\n func listen(_ port: UInt32) throws -> VsockConnectionStream {\n let stream = VsockConnectionStream(port: port)\n let listener = VZVirtioSocketListener()\n listener.delegate = stream\n\n try self.vm.listen(\n queue: queue,\n port: port,\n listener: listener\n )\n return stream\n }\n\n func stopListen(_ port: UInt32) throws {\n try self.vm.removeListener(\n queue: queue,\n port: port\n )\n }\n\n func prestart() async throws {\n if self.config.rosetta {\n #if arch(arm64)\n if VZLinuxRosettaDirectoryShare.availability == .notInstalled {\n self.logger?.info(\"installing rosetta\")\n try await VZVirtualMachineInstance.Configuration.installRosetta()\n }\n #else\n fatalError(\"rosetta is only supported on arm64\")\n #endif\n }\n }\n}\n\nextension VZVirtualMachineInstance.Configuration {\n public static func installRosetta() async throws {\n do {\n #if arch(arm64)\n try await VZLinuxRosettaDirectoryShare.installRosetta()\n #else\n fatalError(\"rosetta is only supported on arm64\")\n #endif\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to install rosetta\",\n cause: error\n )\n }\n }\n\n private func serialPort(path: URL) throws -> [VZVirtioConsoleDeviceSerialPortConfiguration] {\n let c = VZVirtioConsoleDeviceSerialPortConfiguration()\n c.attachment = try VZFileSerialPortAttachment(url: path, append: true)\n return [c]\n }\n\n func toVZ() throws -> VZVirtualMachineConfiguration {\n var config = VZVirtualMachineConfiguration()\n\n config.cpuCount = self.cpus\n config.memorySize = self.memoryInBytes\n config.entropyDevices = [VZVirtioEntropyDeviceConfiguration()]\n config.socketDevices = [VZVirtioSocketDeviceConfiguration()]\n if let bootlog = self.bootlog {\n config.serialPorts = try serialPort(path: bootlog)\n }\n\n config.networkDevices = try self.interfaces.map {\n guard let vzi = $0 as? VZInterface else {\n throw ContainerizationError(.invalidArgument, message: \"interface type not supported by VZ\")\n }\n return try vzi.device()\n }\n\n if self.rosetta {\n #if arch(arm64)\n switch VZLinuxRosettaDirectoryShare.availability {\n case .notSupported:\n throw ContainerizationError(\n .invalidArgument,\n message: \"rosetta was requested but is not supported on this machine\"\n )\n case .notInstalled:\n // NOTE: If rosetta isn't installed, we'll error with a nice error message\n // during .start() of the virtual machine instance.\n fallthrough\n case .installed:\n let share = try VZLinuxRosettaDirectoryShare()\n let device = VZVirtioFileSystemDeviceConfiguration(tag: \"rosetta\")\n device.share = share\n config.directorySharingDevices.append(device)\n @unknown default:\n throw ContainerizationError(\n .invalidArgument,\n message: \"unknown rosetta availability encountered: \\(VZLinuxRosettaDirectoryShare.availability)\"\n )\n }\n #else\n fatalError(\"rosetta is only supported on arm64\")\n #endif\n }\n\n guard let kernel = self.kernel else {\n throw ContainerizationError(.invalidArgument, message: \"kernel cannot be nil\")\n }\n\n guard let initialFilesystem = self.initialFilesystem else {\n throw ContainerizationError(.invalidArgument, message: \"rootfs cannot be nil\")\n }\n\n let loader = VZLinuxBootLoader(kernelURL: kernel.path)\n loader.commandLine = kernel.linuxCommandline(initialFilesystem: initialFilesystem)\n config.bootLoader = loader\n\n try initialFilesystem.configure(config: &config)\n for mount in self.mounts {\n try mount.configure(config: &config)\n }\n\n let platform = VZGenericPlatformConfiguration()\n // We shouldn't silently succeed if the user asked for virt and their hardware does\n // not support it.\n if !VZGenericPlatformConfiguration.isNestedVirtualizationSupported && self.nestedVirtualization {\n throw ContainerizationError(\n .unsupported,\n message: \"nested virtualization is not supported on the platform\"\n )\n }\n platform.isNestedVirtualizationEnabled = self.nestedVirtualization\n config.platform = platform\n\n try config.validate()\n return config\n }\n\n func mountAttachments() throws -> [AttachedFilesystem] {\n let allocator = Character.blockDeviceTagAllocator()\n if let initialFilesystem {\n // When the initial filesystem is a blk, allocate the first letter \"vd(a)\"\n // as that is what this blk will be attached under.\n if initialFilesystem.isBlock {\n _ = try allocator.allocate()\n }\n }\n\n var attachments: [AttachedFilesystem] = []\n for mount in self.mounts {\n attachments.append(try .init(mount: mount, allocator: allocator))\n }\n return attachments\n }\n}\n\nextension Mount {\n var isBlock: Bool {\n type == \"ext4\"\n }\n}\n\nextension Kernel {\n func linuxCommandline(initialFilesystem: Mount) -> String {\n var args = self.commandLine.kernelArgs\n\n args.append(\"init=/sbin/vminitd\")\n // rootfs is always set as ro.\n args.append(\"ro\")\n\n switch initialFilesystem.type {\n case \"virtiofs\":\n args.append(contentsOf: [\n \"rootfstype=virtiofs\",\n \"root=rootfs\",\n ])\n case \"ext4\":\n args.append(contentsOf: [\n \"rootfstype=ext4\",\n \"root=/dev/vda\",\n ])\n default:\n fatalError(\"unsupported initfs filesystem \\(initialFilesystem.type)\")\n }\n\n if self.commandLine.initArgs.count > 0 {\n args.append(\"--\")\n args.append(contentsOf: self.commandLine.initArgs)\n }\n\n return args.joined(separator: \" \")\n }\n}\n\npublic protocol VZInterface {\n func device() throws -> VZVirtioNetworkDeviceConfiguration\n}\n\nextension NATInterface: VZInterface {\n public func device() throws -> VZVirtioNetworkDeviceConfiguration {\n let config = VZVirtioNetworkDeviceConfiguration()\n if let macAddress = self.macAddress {\n guard let mac = VZMACAddress(string: macAddress) else {\n throw ContainerizationError(.invalidArgument, message: \"invalid mac address \\(macAddress)\")\n }\n config.macAddress = mac\n }\n config.attachment = VZNATNetworkDeviceAttachment()\n return config\n }\n}\n\n#endif\n"], ["/containerization/Sources/Containerization/LinuxContainer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\nimport Logging\nimport Synchronization\n\nimport struct ContainerizationOS.Terminal\n\n/// `LinuxContainer` is an easy to use type for launching and managing the\n/// full lifecycle of a Linux container ran inside of a virtual machine.\npublic final class LinuxContainer: Container, Sendable {\n /// The default PATH value for a process.\n public static let defaultPath = \"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\n\n /// The identifier of the container.\n public let id: String\n\n /// Rootfs for the container.\n public let rootfs: Mount\n\n /// Configuration for the container.\n public let config: Configuration\n\n /// The configuration for the LinuxContainer.\n public struct Configuration: Sendable {\n /// Configuration of a container process.\n public struct Process: Sendable {\n /// The arguments for the container process.\n public var arguments: [String] = []\n /// The environment variables for the container process.\n public var environmentVariables: [String] = [\"PATH=\\(LinuxContainer.defaultPath)\"]\n /// The working directory for the container process.\n public var workingDirectory: String = \"/\"\n /// The user the container process will run as.\n public var user: ContainerizationOCI.User = .init()\n /// The rlimits for the container process.\n public var rlimits: [POSIXRlimit] = []\n /// Whether to allocate a pseudo terminal for the process. If you'd like interactive\n /// behavior and are planning to use a terminal for stdin/out/err on the client side,\n /// this should likely be set to true.\n public var terminal: Bool = false\n /// The stdin for the process.\n public var stdin: ReaderStream?\n /// The stdout for the process.\n public var stdout: Writer?\n /// The stderr for the process.\n public var stderr: Writer?\n\n public init() {}\n\n public init(from config: ImageConfig) {\n self.workingDirectory = config.workingDir ?? \"/\"\n self.environmentVariables = config.env ?? []\n self.arguments = (config.entrypoint ?? []) + (config.cmd ?? [])\n self.user = {\n if let rawString = config.user {\n return User(username: rawString)\n }\n return User()\n }()\n }\n\n func toOCI() -> ContainerizationOCI.Process {\n ContainerizationOCI.Process(\n args: self.arguments,\n cwd: self.workingDirectory,\n env: self.environmentVariables,\n user: self.user,\n rlimits: self.rlimits,\n terminal: self.terminal\n )\n }\n\n /// Sets up IO to be handled by the passed in Terminal, and edits the\n /// process configuration to set the necessary state for using a pty.\n mutating public func setTerminalIO(terminal: Terminal) {\n self.environmentVariables.append(\"TERM=xterm\")\n self.terminal = true\n self.stdin = terminal\n self.stdout = terminal\n }\n }\n\n /// Configuration for the init process of the container.\n public var process = Process.init()\n /// The amount of cpus for the container.\n public var cpus: Int = 4\n /// The memory in bytes to give to the container.\n public var memoryInBytes: UInt64 = 1024.mib()\n /// The hostname for the container.\n public var hostname: String = \"\"\n /// The system control options for the container.\n public var sysctl: [String: String] = [:]\n /// The network interfaces for the container.\n public var interfaces: [any Interface] = []\n /// The Unix domain socket relays to setup for the container.\n public var sockets: [UnixSocketConfiguration] = []\n /// Whether rosetta x86-64 emulation should be setup for the container.\n public var rosetta: Bool = false\n /// Whether nested virtualization should be turned on for the container.\n public var virtualization: Bool = false\n /// The mounts for the container.\n public var mounts: [Mount] = LinuxContainer.defaultMounts()\n /// The DNS configuration for the container.\n public var dns: DNS?\n /// The hosts to add to /etc/hosts for the container.\n public var hosts: Hosts?\n\n public init() {}\n }\n\n /// `IOHandler` informs the container process about what should be done\n /// for the stdio streams.\n struct IOHandler: Sendable {\n public var stdin: ReaderStream?\n public var stdout: Writer?\n public var stderr: Writer?\n\n init(stdin: ReaderStream? = nil, stdout: Writer? = nil, stderr: Writer? = nil) {\n self.stdin = stdin\n self.stdout = stdout\n self.stderr = stderr\n }\n }\n\n private let state: Mutex\n\n // Ports to be allocated from for stdio and for\n // unix socket relays that are sharing a guest\n // uds to the host.\n private let hostVsockPorts: Atomic\n // Ports we request the guest to allocate for unix socket relays from\n // the host.\n private let guestVsockPorts: Atomic\n\n private enum State: Sendable {\n /// The container class has been created but no live resources are running.\n case initialized\n /// The container is creating and booting the underlying virtual resources.\n case creating(CreatingState)\n /// The container's virtual machine has been setup and the runtime environment has been configured.\n case created(CreatedState)\n /// The initial process of the container is preparing to start.\n case starting(StartingState)\n /// The initial process of the container has started and is running.\n case started(StartedState)\n /// The container is preparing to stop.\n case stopping(StoppingState)\n /// The container has run and fully stopped.\n case stopped\n /// An error occurred during the lifetime of this class.\n case errored(Swift.Error)\n\n struct CreatingState: Sendable {}\n\n struct CreatedState: Sendable {\n let vm: any VirtualMachineInstance\n let relayManager: UnixSocketRelayManager\n }\n\n struct StartingState: Sendable {\n let vm: any VirtualMachineInstance\n let relayManager: UnixSocketRelayManager\n\n init(_ state: CreatedState) {\n self.vm = state.vm\n self.relayManager = state.relayManager\n }\n }\n\n struct StartedState: Sendable {\n let vm: any VirtualMachineInstance\n let process: LinuxProcess\n let relayManager: UnixSocketRelayManager\n\n init(_ state: StartingState, process: LinuxProcess) {\n self.vm = state.vm\n self.relayManager = state.relayManager\n self.process = process\n }\n }\n\n struct StoppingState: Sendable {\n let vm: any VirtualMachineInstance\n\n init(_ state: StartedState) {\n self.vm = state.vm\n }\n }\n\n mutating func setCreating() throws {\n switch self {\n case .initialized:\n self = .creating(.init())\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in initialized state to start\"\n )\n }\n }\n\n mutating func setCreated(\n vm: any VirtualMachineInstance,\n relayManager: UnixSocketRelayManager\n ) throws {\n switch self {\n case .creating:\n self = .created(.init(vm: vm, relayManager: relayManager))\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in creating state before created\"\n )\n }\n }\n\n mutating func setStarting() throws -> any VirtualMachineInstance {\n switch self {\n case .created(let state):\n self = .starting(.init(state))\n return state.vm\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in created state before starting\"\n )\n }\n }\n\n mutating func setStarted(process: LinuxProcess) throws {\n switch self {\n case .starting(let state):\n self = .started(.init(state, process: process))\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in starting state before started\"\n )\n }\n }\n\n mutating func stopping() throws -> StartedState {\n switch self {\n case .started(let state):\n self = .stopping(.init(state))\n return state\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in a started state before stopping\"\n )\n }\n }\n\n func startedState(_ operation: String) throws -> StartedState {\n switch self {\n case .started(let state):\n return state\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"failed to \\(operation): container must be running\"\n )\n }\n }\n\n mutating func stopped() throws {\n switch self {\n case .stopping(_):\n self = .stopped\n default:\n throw ContainerizationError(\n .invalidState,\n message: \"container must be in a stopping state before setting to stopped\"\n )\n }\n }\n\n mutating func errored(error: Swift.Error) {\n self = .errored(error)\n }\n }\n\n private let vmm: VirtualMachineManager\n private let logger: Logger?\n\n /// Create a new `LinuxContainer`. A `Mount` that contains the contents\n /// of the container image must be provided, as well as a `VirtualMachineManager`\n /// instance that will handle launching the virtual machine the container will\n /// execute inside of.\n public init(\n _ id: String,\n rootfs: Mount,\n vmm: VirtualMachineManager,\n logger: Logger? = nil,\n configuration: (inout Configuration) throws -> Void\n ) throws {\n self.id = id\n self.vmm = vmm\n self.hostVsockPorts = Atomic(0x1000_0000)\n self.guestVsockPorts = Atomic(0x1000_0000)\n self.rootfs = rootfs\n self.logger = logger\n\n var config = Configuration()\n try configuration(&config)\n\n self.config = config\n self.state = Mutex(.initialized)\n }\n\n private static func createDefaultRuntimeSpec(_ id: String) -> Spec {\n .init(\n process: .init(),\n hostname: id,\n root: .init(\n path: Self.guestRootfsPath(id),\n readonly: false\n ),\n linux: .init(\n resources: .init()\n )\n )\n }\n\n private func generateRuntimeSpec() -> Spec {\n var spec = Self.createDefaultRuntimeSpec(id)\n\n // Process toggles.\n spec.process = config.process.toOCI()\n\n // General toggles.\n spec.hostname = config.hostname\n\n // Linux toggles.\n var linux = ContainerizationOCI.Linux.init()\n linux.sysctl = config.sysctl\n spec.linux = linux\n\n return spec\n }\n\n public static func defaultMounts() -> [Mount] {\n let defaultOptions = [\"nosuid\", \"noexec\", \"nodev\"]\n return [\n .any(type: \"proc\", source: \"proc\", destination: \"/proc\", options: defaultOptions),\n .any(type: \"sysfs\", source: \"sysfs\", destination: \"/sys\", options: defaultOptions),\n .any(type: \"devtmpfs\", source: \"none\", destination: \"/dev\", options: [\"nosuid\", \"mode=755\"]),\n .any(type: \"mqueue\", source: \"mqueue\", destination: \"/dev/mqueue\", options: defaultOptions),\n .any(type: \"tmpfs\", source: \"tmpfs\", destination: \"/dev/shm\", options: defaultOptions + [\"mode=1777\", \"size=65536k\"]),\n .any(type: \"cgroup2\", source: \"none\", destination: \"/sys/fs/cgroup\", options: defaultOptions),\n .any(type: \"devpts\", source: \"devpts\", destination: \"/dev/pts\", options: [\"nosuid\", \"noexec\", \"gid=5\", \"mode=620\", \"ptmxmode=666\"]),\n ]\n }\n\n private static func guestRootfsPath(_ id: String) -> String {\n \"/run/container/\\(id)/rootfs\"\n }\n}\n\nextension LinuxContainer {\n package var root: String {\n Self.guestRootfsPath(id)\n }\n\n /// Number of CPU cores allocated.\n public var cpus: Int {\n config.cpus\n }\n\n /// Amount of memory in bytes allocated for the container.\n /// This will be aligned to a 1MB boundary if it isn't already.\n public var memoryInBytes: UInt64 {\n config.memoryInBytes\n }\n\n /// Network interfaces of the container.\n public var interfaces: [any Interface] {\n config.interfaces\n }\n\n /// Create the underlying container's virtual machine\n /// and set up the runtime environment.\n public func create() async throws {\n try self.state.withLock { try $0.setCreating() }\n\n let vm = try vmm.create(container: self)\n try await vm.start()\n do {\n try await vm.withAgent { agent in\n let relayManager = UnixSocketRelayManager(vm: vm)\n\n try await agent.standardSetup()\n\n // Mount the rootfs.\n var rootfs = vm.mounts[0].to\n rootfs.destination = Self.guestRootfsPath(self.id)\n try await agent.mount(rootfs)\n\n // Start up our friendly unix socket relays.\n for socket in self.config.sockets {\n try await self.relayUnixSocket(\n socket: socket,\n relayManager: relayManager,\n agent: agent\n )\n }\n\n // For every interface asked for:\n // 1. Add the address requested\n // 2. Online the adapter\n // 3. If a gateway IP address is present, add the default route.\n for (index, i) in self.interfaces.enumerated() {\n let name = \"eth\\(index)\"\n try await agent.addressAdd(name: name, address: i.address)\n try await agent.up(name: name, mtu: 1280)\n if let gateway = i.gateway {\n try await agent.routeAddDefault(name: name, gateway: gateway)\n }\n }\n\n // Setup /etc/resolv.conf and /etc/hosts if asked for.\n if let dns = self.config.dns {\n try await agent.configureDNS(config: dns, location: rootfs.destination)\n }\n if let hosts = self.config.hosts {\n try await agent.configureHosts(config: hosts, location: rootfs.destination)\n }\n\n try self.state.withLock { try $0.setCreated(vm: vm, relayManager: relayManager) }\n }\n } catch {\n try? await vm.stop()\n self.state.withLock { $0.errored(error: error) }\n throw error\n }\n }\n\n /// Start the container container's initial process.\n public func start() async throws {\n let vm = try self.state.withLock { try $0.setStarting() }\n\n let agent = try await vm.dialAgent()\n do {\n var spec = generateRuntimeSpec()\n // We don't need the rootfs, nor do OCI runtimes want it included.\n spec.mounts = vm.mounts.dropFirst().map { $0.to }\n\n let stdio = Self.setupIO(\n portAllocator: self.hostVsockPorts,\n stdin: self.config.process.stdin,\n stdout: self.config.process.stdout,\n stderr: self.config.process.stderr\n )\n\n let process = LinuxProcess(\n self.id,\n containerID: self.id,\n spec: spec,\n io: stdio,\n agent: agent,\n vm: vm,\n logger: self.logger\n )\n try await process.start()\n\n try self.state.withLock { try $0.setStarted(process: process) }\n } catch {\n try? await agent.close()\n self.state.withLock { $0.errored(error: error) }\n throw error\n }\n }\n\n private static func setupIO(\n portAllocator: borrowing Atomic,\n stdin: ReaderStream?,\n stdout: Writer?,\n stderr: Writer?\n ) -> LinuxProcess.Stdio {\n var stdinSetup: LinuxProcess.StdioReaderSetup? = nil\n if let reader = stdin {\n let ret = portAllocator.wrappingAdd(1, ordering: .relaxed)\n stdinSetup = .init(\n port: ret.oldValue,\n reader: reader\n )\n }\n\n var stdoutSetup: LinuxProcess.StdioSetup? = nil\n if let writer = stdout {\n let ret = portAllocator.wrappingAdd(1, ordering: .relaxed)\n stdoutSetup = LinuxProcess.StdioSetup(\n port: ret.oldValue,\n writer: writer\n )\n }\n\n var stderrSetup: LinuxProcess.StdioSetup? = nil\n if let writer = stderr {\n let ret = portAllocator.wrappingAdd(1, ordering: .relaxed)\n stderrSetup = LinuxProcess.StdioSetup(\n port: ret.oldValue,\n writer: writer\n )\n }\n\n return LinuxProcess.Stdio(\n stdin: stdinSetup,\n stdout: stdoutSetup,\n stderr: stderrSetup\n )\n }\n\n /// Stop the container from executing.\n public func stop() async throws {\n let startedState = try self.state.withLock { try $0.stopping() }\n\n try await startedState.relayManager.stopAll()\n\n // It's possible the state of the vm is not in a great spot\n // if the guest panicked or had any sort of bug/fault.\n // First check if the vm is even still running, as trying to\n // use a vsock handle like below here will cause NIO to\n // fatalError because we'll get an EBADF.\n if startedState.vm.state == .stopped {\n try self.state.withLock { try $0.stopped() }\n return\n }\n\n try await startedState.vm.withAgent { agent in\n // First, we need to stop any unix socket relays as this will\n // keep the rootfs from being able to umount (EBUSY).\n let sockets = config.sockets\n if !sockets.isEmpty {\n guard let relayAgent = agent as? SocketRelayAgent else {\n throw ContainerizationError(\n .unsupported,\n message: \"VirtualMachineAgent does not support relaySocket surface\"\n )\n }\n for socket in sockets {\n try await relayAgent.stopSocketRelay(configuration: socket)\n }\n }\n\n // Now lets ensure every process is donezo.\n try await agent.kill(pid: -1, signal: SIGKILL)\n\n // Wait on init proc exit. Give it 5 seconds of leeway.\n _ = try await agent.waitProcess(\n id: self.id,\n containerID: self.id,\n timeoutInSeconds: 5\n )\n\n // Today, we leave EBUSY looping and other fun logic up to the\n // guest agent.\n try await agent.umount(\n path: Self.guestRootfsPath(self.id),\n flags: 0\n )\n }\n\n // Lets free up the init procs resources, as this includes the open agent conn.\n try? await startedState.process.delete()\n\n try await startedState.vm.stop()\n try self.state.withLock { try $0.stopped() }\n }\n\n /// Send a signal to the container.\n public func kill(_ signal: Int32) async throws {\n let state = try self.state.withLock { try $0.startedState(\"kill\") }\n try await state.process.kill(signal)\n }\n\n /// Wait for the container to exit. Returns the exit code.\n @discardableResult\n public func wait(timeoutInSeconds: Int64? = nil) async throws -> Int32 {\n let state = try self.state.withLock { try $0.startedState(\"wait\") }\n return try await state.process.wait(timeoutInSeconds: timeoutInSeconds)\n }\n\n /// Resize the container's terminal (if one was requested). This\n /// will error if terminal was set to false before creating the container.\n public func resize(to: Terminal.Size) async throws {\n let state = try self.state.withLock { try $0.startedState(\"resize\") }\n try await state.process.resize(to: to)\n }\n\n /// Execute a new process in the container.\n public func exec(_ id: String, configuration: (inout Configuration.Process) throws -> Void) async throws -> LinuxProcess {\n let state = try self.state.withLock { try $0.startedState(\"exec\") }\n\n var spec = generateRuntimeSpec()\n var config = Configuration.Process()\n try configuration(&config)\n spec.process = config.toOCI()\n\n let stdio = Self.setupIO(\n portAllocator: self.hostVsockPorts,\n stdin: config.stdin,\n stdout: config.stdout,\n stderr: config.stderr\n )\n let agent = try await state.vm.dialAgent()\n let process = LinuxProcess(\n id,\n containerID: self.id,\n spec: spec,\n io: stdio,\n agent: agent,\n vm: state.vm,\n logger: self.logger\n )\n return process\n }\n\n /// Execute a new process in the container.\n public func exec(_ id: String, configuration: Configuration.Process) async throws -> LinuxProcess {\n let state = try self.state.withLock { try $0.startedState(\"exec\") }\n\n var spec = generateRuntimeSpec()\n spec.process = configuration.toOCI()\n\n let stdio = Self.setupIO(\n portAllocator: self.hostVsockPorts,\n stdin: configuration.stdin,\n stdout: configuration.stdout,\n stderr: configuration.stderr\n )\n let agent = try await state.vm.dialAgent()\n let process = LinuxProcess(\n id,\n containerID: self.id,\n spec: spec,\n io: stdio,\n agent: agent,\n vm: state.vm,\n logger: self.logger\n )\n return process\n }\n\n /// Dial a vsock port in the container.\n public func dialVsock(port: UInt32) async throws -> FileHandle {\n let state = try self.state.withLock { try $0.startedState(\"dialVsock\") }\n return try await state.vm.dial(port)\n }\n\n /// Close the containers standard input to signal no more input is\n /// arriving.\n public func closeStdin() async throws {\n let state = try self.state.withLock { try $0.startedState(\"closeStdin\") }\n return try await state.process.closeStdin()\n }\n\n /// Relay a unix socket from in the container to the host, or from the host\n /// to inside the container.\n public func relayUnixSocket(socket: UnixSocketConfiguration) async throws {\n let state = try self.state.withLock { try $0.startedState(\"relayUnixSocket\") }\n\n try await state.vm.withAgent { agent in\n try await self.relayUnixSocket(\n socket: socket,\n relayManager: state.relayManager,\n agent: agent\n )\n }\n }\n\n private func relayUnixSocket(\n socket: UnixSocketConfiguration,\n relayManager: UnixSocketRelayManager,\n agent: any VirtualMachineAgent\n ) async throws {\n guard let relayAgent = agent as? SocketRelayAgent else {\n throw ContainerizationError(\n .unsupported,\n message: \"VirtualMachineAgent does not support relaySocket surface\"\n )\n }\n\n var socket = socket\n let rootInGuest = URL(filePath: self.root)\n\n if socket.direction == .into {\n socket.destination = rootInGuest.appending(path: socket.destination.path)\n } else {\n socket.source = rootInGuest.appending(path: socket.source.path)\n }\n\n let port = self.hostVsockPorts.wrappingAdd(1, ordering: .relaxed).oldValue\n try await relayManager.start(port: port, socket: socket)\n try await relayAgent.relaySocket(port: port, configuration: socket)\n }\n}\n\nextension VirtualMachineInstance {\n /// Scoped access to an agent instance to ensure the resources are always freed (mostly close(2)'ing\n /// the vsock fd)\n fileprivate func withAgent(fn: @Sendable (VirtualMachineAgent) async throws -> Void) async throws {\n let agent = try await self.dialAgent()\n do {\n try await fn(agent)\n try await agent.close()\n } catch {\n try? await agent.close()\n throw error\n }\n }\n}\n\nextension AttachedFilesystem {\n fileprivate var to: ContainerizationOCI.Mount {\n .init(\n type: self.type,\n source: self.source,\n destination: self.destination,\n options: self.options\n )\n }\n}\n\n#endif\n"], ["/containerization/Sources/ContainerizationExtras/IndexedAddressAllocator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Collections\nimport Synchronization\n\n/// Maps a network address to an array index value, or nil in the case of a domain error.\npackage typealias AddressToIndexTransform = @Sendable (AddressType) -> Int?\n\n/// Maps an array index value to a network address, or nil in the case of a domain error.\npackage typealias IndexToAddressTransform = @Sendable (Int) -> AddressType?\n\npackage final class IndexedAddressAllocator: AddressAllocator {\n private class State {\n var allocations: BitArray\n var enabled: Bool\n var allocationCount: Int\n let addressToIndex: AddressToIndexTransform\n let indexToAddress: IndexToAddressTransform\n\n init(\n size: Int,\n addressToIndex: @escaping AddressToIndexTransform,\n indexToAddress: @escaping IndexToAddressTransform\n ) {\n self.allocations = BitArray.init(repeating: false, count: size)\n self.enabled = true\n self.allocationCount = 0\n self.addressToIndex = addressToIndex\n self.indexToAddress = indexToAddress\n }\n }\n\n private let stateGuard: Mutex\n\n /// Create an allocator with specified size and index mappings.\n package init(\n size: Int,\n addressToIndex: @escaping AddressToIndexTransform,\n indexToAddress: @escaping IndexToAddressTransform\n ) {\n let state = State(\n size: size,\n addressToIndex: addressToIndex,\n indexToAddress: indexToAddress\n )\n self.stateGuard = Mutex(state)\n }\n\n public func allocate() throws -> AddressType {\n try self.stateGuard.withLock { state in\n guard state.enabled else {\n throw AllocatorError.allocatorDisabled\n }\n\n guard let index = state.allocations.firstIndex(of: false) else {\n throw AllocatorError.allocatorFull\n }\n\n guard let address = state.indexToAddress(index) else {\n throw AllocatorError.invalidIndex(index)\n }\n\n state.allocations[index] = true\n state.allocationCount += 1\n return address\n }\n }\n\n package func reserve(_ address: AddressType) throws {\n try self.stateGuard.withLock { state in\n guard state.enabled else {\n throw AllocatorError.allocatorDisabled\n }\n\n guard let index = state.addressToIndex(address) else {\n throw AllocatorError.invalidAddress(address.description)\n }\n\n guard !state.allocations[index] else {\n throw AllocatorError.alreadyAllocated(\"\\(address.description)\")\n }\n\n state.allocations[index] = true\n state.allocationCount += 1\n }\n\n }\n\n package func release(_ address: AddressType) throws {\n try self.stateGuard.withLock { state in\n guard let index = state.addressToIndex(address) else {\n throw AllocatorError.invalidAddress(address.description)\n }\n\n guard state.allocations[index] else {\n throw AllocatorError.notAllocated(\"\\(address.description)\")\n }\n\n state.allocations[index] = false\n state.allocationCount -= 1\n }\n }\n\n package func disableAllocator() -> Bool {\n self.stateGuard.withLock { state in\n guard state.allocationCount == 0 else {\n return false\n }\n state.enabled = false\n return true\n }\n }\n}\n"], ["/containerization/Sources/Containerization/NATInterface.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic struct NATInterface: Interface {\n public var address: String\n public var gateway: String?\n public var macAddress: String?\n\n public init(address: String, gateway: String?, macAddress: String? = nil) {\n self.address = address\n self.gateway = gateway\n self.macAddress = macAddress\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/RotatingAddressAllocator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Synchronization\n\npackage final class RotatingAddressAllocator: AddressAllocator {\n package typealias AddressType = UInt32\n\n private struct State {\n var allocations: [AddressType]\n var enabled: Bool\n var allocationCount: Int\n let addressToIndex: AddressToIndexTransform\n let indexToAddress: IndexToAddressTransform\n\n init(\n size: UInt32,\n addressToIndex: @escaping AddressToIndexTransform,\n indexToAddress: @escaping IndexToAddressTransform\n ) {\n self.allocations = [UInt32](0..\n\n /// Create an allocator with specified size and index mappings.\n package init(\n size: UInt32,\n addressToIndex: @escaping AddressToIndexTransform,\n indexToAddress: @escaping IndexToAddressTransform\n ) {\n let state = State(\n size: size,\n addressToIndex: addressToIndex,\n indexToAddress: indexToAddress\n )\n self.stateGuard = Mutex(state)\n }\n\n public func allocate() throws -> AddressType {\n try self.stateGuard.withLock { state in\n guard state.enabled else {\n throw AllocatorError.allocatorDisabled\n }\n\n guard state.allocations.count > 0 else {\n throw AllocatorError.allocatorFull\n }\n\n let value = state.allocations.removeFirst()\n\n guard let address = state.indexToAddress(Int(value)) else {\n throw AllocatorError.invalidIndex(Int(value))\n }\n\n state.allocationCount += 1\n return address\n }\n }\n\n package func reserve(_ address: AddressType) throws {\n try self.stateGuard.withLock { state in\n guard state.enabled else {\n throw AllocatorError.allocatorDisabled\n }\n\n guard let index = state.addressToIndex(address) else {\n throw AllocatorError.invalidAddress(address.description)\n }\n\n let i = state.allocations.firstIndex(of: UInt32(index))\n guard let i else {\n throw AllocatorError.alreadyAllocated(\"\\(address.description)\")\n }\n\n _ = state.allocations.remove(at: i)\n state.allocationCount += 1\n }\n }\n\n package func release(_ address: AddressType) throws {\n try self.stateGuard.withLock { state in\n guard let index = (state.addressToIndex(address)) else {\n throw AllocatorError.invalidAddress(address.description)\n }\n let value = UInt32(index)\n\n guard !state.allocations.contains(value) else {\n throw AllocatorError.notAllocated(\"\\(address.description)\")\n }\n\n state.allocations.append(value)\n state.allocationCount -= 1\n }\n }\n\n package func disableAllocator() -> Bool {\n self.stateGuard.withLock { state in\n guard state.allocationCount == 0 else {\n return false\n }\n state.enabled = false\n return true\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Socket/Socket.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Synchronization\n\n#if canImport(Musl)\nimport Musl\n#elseif canImport(Glibc)\nimport Glibc\n#elseif canImport(Darwin)\nimport Darwin\n#else\n#error(\"Socket not supported on this platform.\")\n#endif\n\n#if !os(Windows)\nlet sysFchmod = fchmod\nlet sysRead = read\nlet sysUnlink = unlink\nlet sysSend = send\nlet sysClose = close\nlet sysShutdown = shutdown\nlet sysBind = bind\nlet sysSocket = socket\nlet sysSetsockopt = setsockopt\nlet sysGetsockopt = getsockopt\nlet sysListen = listen\nlet sysAccept = accept\nlet sysConnect = connect\nlet sysIoctl: @convention(c) (CInt, CUnsignedLong, UnsafeMutableRawPointer) -> CInt = ioctl\n#endif\n\n/// Thread-safe socket wrapper.\npublic final class Socket: Sendable {\n public enum TimeoutOption {\n case send\n case receive\n }\n\n public enum ShutdownOption {\n case read\n case write\n case readWrite\n }\n\n private enum SocketState {\n case created\n case connected\n case listening\n }\n\n private struct State {\n let socketState: SocketState\n let handle: FileHandle?\n let type: SocketType\n let acceptSource: DispatchSourceRead?\n }\n\n private let _closeOnDeinit: Bool\n private let _queue: DispatchQueue\n\n private let state: Mutex\n\n public var fileDescriptor: Int32 {\n guard let handle = state.withLock({ $0.handle }) else {\n return -1\n }\n return handle.fileDescriptor\n }\n\n public convenience init(type: SocketType, closeOnDeinit: Bool = true) throws {\n let sockFD = sysSocket(type.domain, type.type, 0)\n if sockFD < 0 {\n throw SocketError.withErrno(\"failed to create socket: \\(sockFD)\", errno: errno)\n }\n self.init(fd: sockFD, type: type, closeOnDeinit: closeOnDeinit)\n }\n\n init(fd: Int32, type: SocketType, closeOnDeinit: Bool) {\n _queue = DispatchQueue(label: \"com.apple.containerization.socket\")\n _closeOnDeinit = closeOnDeinit\n let state = State(\n socketState: .created,\n handle: FileHandle(fileDescriptor: fd, closeOnDealloc: false),\n type: type,\n acceptSource: nil\n )\n self.state = Mutex(state)\n }\n\n deinit {\n if _closeOnDeinit {\n try? close()\n }\n }\n}\n\nextension Socket {\n static func errnoToError(msg: String) -> SocketError {\n SocketError.withErrno(\"\\(msg) (\\(_errnoString(errno)))\", errno: errno)\n }\n\n public func connect() throws {\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n guard state.withLock({ $0.socketState }) == .created else {\n throw SocketError.invalidOperationOnSocket(\"connect\")\n }\n\n var res: Int32 = 0\n try state.withLock {\n try $0.type.withSockAddr { (ptr, length) in\n res = Syscall.retrying {\n sysConnect(handle.fileDescriptor, ptr, length)\n }\n }\n }\n if res == -1 {\n throw Socket.errnoToError(msg: \"could not connect to socket \\(state.withLock { $0.type })\")\n }\n state.withLock {\n $0 = State(\n socketState: .connected,\n handle: handle,\n type: $0.type,\n acceptSource: $0.acceptSource\n )\n }\n }\n\n public func listen() throws {\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n guard state.withLock({ $0.socketState }) == .created else {\n throw SocketError.invalidOperationOnSocket(\"listen\")\n }\n\n try state.withLock { try $0.type.beforeBind(fd: handle.fileDescriptor) }\n\n var rc: Int32 = 0\n try state.withLock {\n try $0.type.withSockAddr { (ptr, length) in\n rc = sysBind(handle.fileDescriptor, ptr, length)\n }\n }\n if rc < 0 {\n throw Socket.errnoToError(msg: \"could not bind to \\(state.withLock { $0.type })\")\n }\n\n try state.withLock { try $0.type.beforeListen(fd: handle.fileDescriptor) }\n if sysListen(handle.fileDescriptor, SOMAXCONN) < 0 {\n throw Socket.errnoToError(msg: \"listen failed on \\(state.withLock { $0.type })\")\n }\n state.withLock {\n $0 = State(\n socketState: .listening,\n handle: handle,\n type: $0.type,\n acceptSource: $0.acceptSource\n )\n }\n }\n\n public func close() throws {\n // Already closed.\n guard let handle = state.withLock({ $0.handle }) else {\n return\n }\n if let acceptSource = state.withLock({ $0.acceptSource }) {\n acceptSource.cancel()\n }\n try handle.close()\n state.withLock {\n $0 = State(\n socketState: $0.socketState,\n handle: nil,\n type: $0.type,\n acceptSource: nil\n )\n }\n }\n\n public func write(data: any DataProtocol) throws -> Int {\n guard state.withLock({ $0.socketState }) == .connected else {\n throw SocketError.invalidOperationOnSocket(\"write\")\n }\n\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n if data.isEmpty {\n return 0\n }\n\n try handle.write(contentsOf: data)\n return data.count\n }\n\n public func acceptStream(closeOnDeinit: Bool = true) throws -> AsyncThrowingStream {\n guard state.withLock({ $0.socketState }) == .listening else {\n throw SocketError.invalidOperationOnSocket(\"accept\")\n }\n\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n guard state.withLock({ $0.acceptSource }) == nil else {\n throw SocketError.acceptStreamExists\n }\n\n let source = state.withLock {\n let source = DispatchSource.makeReadSource(\n fileDescriptor: handle.fileDescriptor,\n queue: _queue\n )\n $0 = State(\n socketState: $0.socketState,\n handle: handle,\n type: $0.type,\n acceptSource: source\n )\n return source\n }\n\n return AsyncThrowingStream { cont in\n source.setCancelHandler {\n cont.finish()\n }\n source.setEventHandler(handler: {\n if source.data == 0 {\n source.cancel()\n return\n }\n\n do {\n let connection = try self.accept(closeOnDeinit: closeOnDeinit)\n cont.yield(connection)\n } catch SocketError.closed {\n source.cancel()\n } catch {\n cont.yield(with: .failure(error))\n source.cancel()\n }\n })\n source.activate()\n }\n }\n\n public func accept(closeOnDeinit: Bool = true) throws -> Socket {\n guard state.withLock({ $0.socketState }) == .listening else {\n throw SocketError.invalidOperationOnSocket(\"accept\")\n }\n\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n let (clientFD, socketType) = try state.withLock { try $0.type.accept(fd: handle.fileDescriptor) }\n return Socket(\n fd: clientFD,\n type: socketType,\n closeOnDeinit: closeOnDeinit\n )\n }\n\n public func read(buffer: inout Data) throws -> Int {\n guard state.withLock({ $0.socketState }) == .connected else {\n throw SocketError.invalidOperationOnSocket(\"read\")\n }\n\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n var bytesRead = 0\n let bufferSize = buffer.count\n try buffer.withUnsafeMutableBytes { pointer in\n guard let baseAddress = pointer.baseAddress else {\n throw SocketError.missingBaseAddress\n }\n\n bytesRead = Syscall.retrying {\n sysRead(handle.fileDescriptor, baseAddress, bufferSize)\n }\n if bytesRead < 0 {\n throw Socket.errnoToError(msg: \"Error reading from connection\")\n } else if bytesRead == 0 {\n throw SocketError.closed\n }\n }\n return bytesRead\n }\n\n public func shutdown(how: ShutdownOption) throws {\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n var howOpt: Int32 = 0\n switch how {\n case .read:\n howOpt = Int32(SHUT_RD)\n case .write:\n howOpt = Int32(SHUT_WR)\n case .readWrite:\n howOpt = Int32(SHUT_RDWR)\n }\n\n if sysShutdown(handle.fileDescriptor, howOpt) < 0 {\n throw Socket.errnoToError(msg: \"shutdown failed\")\n }\n }\n\n public func setSockOpt(sockOpt: Int32 = 0, ptr: UnsafeRawPointer, stride: UInt32) throws {\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n if setsockopt(handle.fileDescriptor, SOL_SOCKET, sockOpt, ptr, stride) < 0 {\n throw Socket.errnoToError(msg: \"failed to set sockopt\")\n }\n }\n\n public func setTimeout(option: TimeoutOption, seconds: Int) throws {\n guard let handle = state.withLock({ $0.handle }) else {\n throw SocketError.closed\n }\n\n var sockOpt: Int32 = 0\n switch option {\n case .receive:\n sockOpt = SO_RCVTIMEO\n case .send:\n sockOpt = SO_SNDTIMEO\n }\n\n var timer = timeval()\n timer.tv_sec = seconds\n timer.tv_usec = 0\n\n if setsockopt(\n handle.fileDescriptor,\n SOL_SOCKET,\n sockOpt,\n &timer,\n socklen_t(MemoryLayout.size)\n ) < 0 {\n throw Socket.errnoToError(msg: \"failed to set read timeout\")\n }\n }\n\n static func _errnoString(_ err: Int32?) -> String {\n String(validatingCString: strerror(errno)) ?? \"error: \\(errno)\"\n }\n}\n\npublic enum SocketError: Error, Equatable, CustomStringConvertible {\n case closed\n case acceptStreamExists\n case invalidOperationOnSocket(String)\n case missingBaseAddress\n case withErrno(_ msg: String, errno: Int32)\n\n public var description: String {\n switch self {\n case .closed:\n return \"socket: closed\"\n case .acceptStreamExists:\n return \"accept stream already exists\"\n case .invalidOperationOnSocket(let operation):\n return \"socket: invalid operation on socket '\\(operation)'\"\n case .missingBaseAddress:\n return \"socket: missing base address\"\n case .withErrno(let msg, _):\n return \"socket: error \\(msg)\"\n }\n }\n}\n"], ["/containerization/Sources/Containerization/UnixSocketRelay.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationIO\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport Synchronization\n\npackage actor UnixSocketRelayManager {\n private let vm: any VirtualMachineInstance\n private var relays: [String: SocketRelay]\n private let q: DispatchQueue\n private let log: Logger?\n\n init(vm: any VirtualMachineInstance, log: Logger? = nil) {\n self.vm = vm\n self.relays = [:]\n self.q = DispatchQueue(label: \"com.apple.containerization.socket-relay\")\n self.log = log\n }\n}\n\nextension UnixSocketRelayManager {\n func start(port: UInt32, socket: UnixSocketConfiguration) async throws {\n guard self.relays[socket.id] == nil else {\n throw ContainerizationError(\n .invalidState,\n message: \"socket relay \\(socket.id) already started\"\n )\n }\n\n let socketRelay = try SocketRelay(\n port: port,\n socket: socket,\n vm: self.vm,\n queue: self.q,\n log: self.log\n )\n\n do {\n self.relays[socket.id] = socketRelay\n try await socketRelay.start()\n } catch {\n self.relays.removeValue(forKey: socket.id)\n }\n }\n\n func stop(socket: UnixSocketConfiguration) async throws {\n guard let storedRelay = self.relays.removeValue(forKey: socket.id) else {\n throw ContainerizationError(\n .notFound,\n message: \"failed to stop socket relay\"\n )\n }\n try storedRelay.stop()\n }\n\n func stopAll() async throws {\n for (_, relay) in self.relays {\n try relay.stop()\n }\n }\n}\n\npackage final class SocketRelay: Sendable {\n private let port: UInt32\n private let configuration: UnixSocketConfiguration\n private let log: Logger?\n private let vm: any VirtualMachineInstance\n private let q: DispatchQueue\n private let state: Mutex\n\n private struct State {\n var relaySources: [String: ConnectionSources] = [:]\n var t: Task<(), Never>? = nil\n }\n\n // `DispatchSourceRead` is thread-safe.\n private struct ConnectionSources: @unchecked Sendable {\n let hostSource: DispatchSourceRead\n let guestSource: DispatchSourceRead\n }\n\n init(\n port: UInt32,\n socket: UnixSocketConfiguration,\n vm: any VirtualMachineInstance,\n queue: DispatchQueue,\n log: Logger? = nil\n ) throws {\n self.port = port\n self.configuration = socket\n self.state = Mutex(.init())\n self.vm = vm\n self.log = log\n self.q = queue\n }\n\n deinit {\n self.state.withLock { $0.t?.cancel() }\n }\n}\n\nextension SocketRelay {\n func start() async throws {\n switch configuration.direction {\n case .outOf:\n try await setupHostVsockDial()\n case .into:\n try setupHostVsockListener()\n }\n }\n\n func stop() throws {\n try self.state.withLock {\n guard let t = $0.t else {\n throw ContainerizationError(\n .invalidState,\n message: \"failed to stop socket relay: relay has not been started\"\n )\n }\n t.cancel()\n $0.t = nil\n $0.relaySources.removeAll()\n }\n\n switch configuration.direction {\n case .outOf:\n // If we created the host conn, lets unlink it also. It's possible it was\n // already unlinked if the relay failed earlier.\n try? FileManager.default.removeItem(at: self.configuration.destination)\n case .into:\n try self.vm.stopListen(self.port)\n }\n }\n\n private func setupHostVsockDial() async throws {\n let hostConn = self.configuration.destination\n\n let socketType = try UnixType(\n path: hostConn.path,\n unlinkExisting: true\n )\n let hostSocket = try Socket(type: socketType)\n try hostSocket.listen()\n\n let connectionStream = try hostSocket.acceptStream(closeOnDeinit: false)\n self.state.withLock {\n $0.t = Task {\n do {\n for try await connection in connectionStream {\n try await self.handleHostUnixConn(\n hostConn: connection,\n port: self.port,\n vm: self.vm,\n log: self.log\n )\n }\n } catch {\n log?.error(\"failed in unix socket relay loop: \\(error)\")\n }\n try? FileManager.default.removeItem(at: hostConn)\n }\n }\n }\n\n private func setupHostVsockListener() throws {\n let hostPath = self.configuration.source\n let port = self.port\n let log = self.log\n\n let connectionStream = try self.vm.listen(self.port)\n self.state.withLock {\n $0.t = Task {\n do {\n defer { connectionStream.finish() }\n for await connection in connectionStream.connections {\n try await self.handleGuestVsockConn(\n vsockConn: connection,\n hostConnectionPath: hostPath,\n port: port,\n log: log\n )\n }\n } catch {\n log?.error(\"failed to setup relay between vsock \\(port) and \\(hostPath.path): \\(error)\")\n }\n }\n }\n }\n\n private func handleHostUnixConn(\n hostConn: ContainerizationOS.Socket,\n port: UInt32,\n vm: any VirtualMachineInstance,\n log: Logger?\n ) async throws {\n do {\n let guestConn = try await vm.dial(port)\n try await self.relay(\n hostConn: hostConn,\n guestFd: guestConn.fileDescriptor\n )\n } catch {\n log?.error(\"failed to relay between vsock \\(port) and \\(hostConn)\")\n throw error\n }\n }\n\n private func handleGuestVsockConn(\n vsockConn: FileHandle,\n hostConnectionPath: URL,\n port: UInt32,\n log: Logger?\n ) async throws {\n let hostPath = hostConnectionPath.path\n let socketType = try UnixType(path: hostPath)\n let hostSocket = try Socket(\n type: socketType,\n closeOnDeinit: false\n )\n try hostSocket.connect()\n\n do {\n try await self.relay(\n hostConn: hostSocket,\n guestFd: vsockConn.fileDescriptor\n )\n } catch {\n log?.error(\"failed to relay between vsock \\(port) and \\(hostPath)\")\n }\n }\n\n private func relay(\n hostConn: Socket,\n guestFd: Int32\n ) async throws {\n let connSource = DispatchSource.makeReadSource(\n fileDescriptor: hostConn.fileDescriptor,\n queue: self.q\n )\n let vsockConnectionSource = DispatchSource.makeReadSource(\n fileDescriptor: guestFd,\n queue: self.q\n )\n\n let pairID = UUID().uuidString\n self.state.withLock {\n $0.relaySources[pairID] = ConnectionSources(\n hostSource: connSource,\n guestSource: vsockConnectionSource\n )\n }\n\n nonisolated(unsafe) let buf1 = UnsafeMutableBufferPointer.allocate(capacity: Int(getpagesize()))\n connSource.setEventHandler {\n Self.fdCopyHandler(\n buffer: buf1,\n source: connSource,\n from: hostConn.fileDescriptor,\n to: guestFd\n )\n }\n\n nonisolated(unsafe) let buf2 = UnsafeMutableBufferPointer.allocate(capacity: Int(getpagesize()))\n vsockConnectionSource.setEventHandler {\n Self.fdCopyHandler(\n buffer: buf2,\n source: vsockConnectionSource,\n from: guestFd,\n to: hostConn.fileDescriptor\n )\n }\n\n connSource.setCancelHandler {\n if !connSource.isCancelled {\n connSource.cancel()\n }\n if !vsockConnectionSource.isCancelled {\n vsockConnectionSource.cancel()\n }\n try? hostConn.close()\n }\n\n vsockConnectionSource.setCancelHandler {\n if !vsockConnectionSource.isCancelled {\n vsockConnectionSource.cancel()\n }\n if !connSource.isCancelled {\n connSource.cancel()\n }\n close(guestFd)\n }\n\n connSource.activate()\n vsockConnectionSource.activate()\n }\n\n private static func fdCopyHandler(\n buffer: UnsafeMutableBufferPointer,\n source: DispatchSourceRead,\n from sourceFd: Int32,\n to destinationFd: Int32,\n log: Logger? = nil\n ) {\n if source.data == 0 {\n if !source.isCancelled {\n source.cancel()\n }\n return\n }\n\n do {\n try self.fileDescriptorCopy(\n buffer: buffer,\n size: source.data,\n from: sourceFd,\n to: destinationFd\n )\n } catch {\n log?.error(\"file descriptor copy failed \\(error)\")\n if !source.isCancelled {\n source.cancel()\n }\n }\n }\n\n private static func fileDescriptorCopy(\n buffer: UnsafeMutableBufferPointer,\n size: UInt,\n from sourceFd: Int32,\n to destinationFd: Int32\n ) throws {\n let bufferSize = buffer.count\n var readBytesRemaining = min(Int(size), bufferSize)\n\n guard let baseAddr = buffer.baseAddress else {\n throw ContainerizationError(\n .invalidState,\n message: \"buffer has no base address\"\n )\n }\n\n while readBytesRemaining > 0 {\n let readResult = read(sourceFd, baseAddr, min(bufferSize, readBytesRemaining))\n if readResult <= 0 {\n throw ContainerizationError(\n .internalError,\n message: \"missing pointer base address\"\n )\n }\n readBytesRemaining -= readResult\n\n var writeBytesRemaining = readResult\n while writeBytesRemaining > 0 {\n let writeResult = write(destinationFd, baseAddr, writeBytesRemaining)\n if writeResult <= 0 {\n throw ContainerizationError(\n .internalError,\n message: \"zero byte write or error in socket relay\"\n )\n }\n writeBytesRemaining -= writeResult\n }\n }\n }\n}\n"], ["/containerization/Sources/Containerization/Agent/Vminitd.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport GRPC\nimport NIOPosix\n\n/// A remote connection into the vminitd Linux guest agent via a port (vsock).\n/// Used to modify the runtime environment of the Linux sandbox.\npublic struct Vminitd: Sendable {\n public typealias Client = Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClient\n\n // Default vsock port that the agent and client use.\n public static let port: UInt32 = 1024\n\n private static let defaultPath = \"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\n\n let client: Client\n\n public init(client: Client) {\n self.client = client\n }\n\n public init(connection: FileHandle, group: MultiThreadedEventLoopGroup) {\n self.client = .init(connection: connection, group: group)\n }\n\n /// Close the connection to the guest agent.\n public func close() async throws {\n try await client.close()\n }\n}\n\nextension Vminitd: VirtualMachineAgent {\n /// Perform the standard guest setup necessary for vminitd to be able to\n /// run containers.\n public func standardSetup() async throws {\n try await up(name: \"lo\")\n\n try await setenv(key: \"PATH\", value: Self.defaultPath)\n\n let mounts: [ContainerizationOCI.Mount] = [\n // NOTE: /proc is always done implicitly by the guest agent.\n .init(type: \"tmpfs\", source: \"tmpfs\", destination: \"/run\"),\n .init(type: \"sysfs\", source: \"sysfs\", destination: \"/sys\"),\n .init(type: \"tmpfs\", source: \"tmpfs\", destination: \"/tmp\"),\n .init(type: \"devpts\", source: \"devpts\", destination: \"/dev/pts\", options: [\"gid=5\", \"mode=620\", \"ptmxmode=666\"]),\n .init(type: \"cgroup2\", source: \"none\", destination: \"/sys/fs/cgroup\"),\n ]\n for mount in mounts {\n try await self.mount(mount)\n }\n }\n\n /// Mount a filesystem in the sandbox's environment.\n public func mount(_ mount: ContainerizationOCI.Mount) async throws {\n _ = try await client.mount(\n .with {\n $0.type = mount.type\n $0.source = mount.source\n $0.destination = mount.destination\n $0.options = mount.options\n })\n }\n\n /// Unmount a filesystem in the sandbox's environment.\n public func umount(path: String, flags: Int32) async throws {\n _ = try await client.umount(\n .with {\n $0.path = path\n $0.flags = flags\n })\n }\n\n /// Create a directory inside the sandbox's environment.\n public func mkdir(path: String, all: Bool, perms: UInt32) async throws {\n _ = try await client.mkdir(\n .with {\n $0.path = path\n $0.all = all\n $0.perms = perms\n })\n }\n\n public func createProcess(\n id: String,\n containerID: String?,\n stdinPort: UInt32?,\n stdoutPort: UInt32?,\n stderrPort: UInt32?,\n configuration: ContainerizationOCI.Spec,\n options: Data?\n ) async throws {\n let enc = JSONEncoder()\n _ = try await client.createProcess(\n .with {\n $0.id = id\n if let stdinPort {\n $0.stdin = stdinPort\n }\n if let stdoutPort {\n $0.stdout = stdoutPort\n }\n if let stderrPort {\n $0.stderr = stderrPort\n }\n if let containerID {\n $0.containerID = containerID\n }\n $0.configuration = try enc.encode(configuration)\n })\n }\n\n @discardableResult\n public func startProcess(id: String, containerID: String?) async throws -> Int32 {\n let request = Com_Apple_Containerization_Sandbox_V3_StartProcessRequest.with {\n $0.id = id\n if let containerID {\n $0.containerID = containerID\n }\n }\n let resp = try await client.startProcess(request)\n return resp.pid\n }\n\n public func signalProcess(id: String, containerID: String?, signal: Int32) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_KillProcessRequest.with {\n $0.id = id\n $0.signal = signal\n if let containerID {\n $0.containerID = containerID\n }\n }\n _ = try await client.killProcess(request)\n }\n\n public func resizeProcess(id: String, containerID: String?, columns: UInt32, rows: UInt32) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest.with {\n if let containerID {\n $0.containerID = containerID\n }\n $0.id = id\n $0.columns = columns\n $0.rows = rows\n }\n _ = try await client.resizeProcess(request)\n }\n\n public func waitProcess(id: String, containerID: String?, timeoutInSeconds: Int64? = nil) async throws -> Int32 {\n let request = Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest.with {\n $0.id = id\n if let containerID {\n $0.containerID = containerID\n }\n }\n var callOpts: CallOptions?\n if let timeoutInSeconds {\n var copts = CallOptions()\n copts.timeLimit = .timeout(.seconds(timeoutInSeconds))\n callOpts = copts\n }\n do {\n let resp = try await client.waitProcess(request, callOptions: callOpts)\n return resp.exitCode\n } catch {\n if let err = error as? GRPCError.RPCTimedOut {\n throw ContainerizationError(\n .timeout,\n message: \"failed to wait for process exit within timeout of \\(timeoutInSeconds!) seconds\",\n cause: err\n )\n }\n throw error\n }\n }\n\n public func deleteProcess(id: String, containerID: String?) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest.with {\n $0.id = id\n if let containerID {\n $0.containerID = containerID\n }\n }\n _ = try await client.deleteProcess(request)\n }\n\n public func closeProcessStdin(id: String, containerID: String?) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest.with {\n $0.id = id\n if let containerID {\n $0.containerID = containerID\n }\n }\n _ = try await client.closeProcessStdin(request)\n }\n\n public func up(name: String, mtu: UInt32? = nil) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest.with {\n $0.interface = name\n $0.up = true\n if let mtu { $0.mtu = mtu }\n }\n _ = try await client.ipLinkSet(request)\n }\n\n public func down(name: String) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest.with {\n $0.interface = name\n $0.up = false\n }\n _ = try await client.ipLinkSet(request)\n }\n\n /// Get an environment variable from the sandbox's environment.\n public func getenv(key: String) async throws -> String {\n let response = try await client.getenv(\n .with {\n $0.key = key\n })\n return response.value\n }\n\n /// Set an environment variable in the sandbox's environment.\n public func setenv(key: String, value: String) async throws {\n _ = try await client.setenv(\n .with {\n $0.key = key\n $0.value = value\n })\n }\n}\n\n/// Vminitd specific rpcs.\nextension Vminitd {\n /// Sets up an emulator in the guest.\n public func setupEmulator(binaryPath: String, configuration: Binfmt.Entry) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest.with {\n $0.binaryPath = binaryPath\n $0.name = configuration.name\n $0.type = configuration.type\n $0.offset = configuration.offset\n $0.magic = configuration.magic\n $0.mask = configuration.mask\n $0.flags = configuration.flags\n }\n _ = try await client.setupEmulator(request)\n }\n\n /// Sets the guest time.\n public func setTime(sec: Int64, usec: Int32) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_SetTimeRequest.with {\n $0.sec = sec\n $0.usec = usec\n }\n _ = try await client.setTime(request)\n }\n\n /// Set the provided sysctls inside the Sandbox's environment.\n public func sysctl(settings: [String: String]) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_SysctlRequest.with {\n $0.settings = settings\n }\n _ = try await client.sysctl(request)\n }\n\n /// Add an IP address to the sandbox's network interfaces.\n public func addressAdd(name: String, address: String) async throws {\n _ = try await client.ipAddrAdd(\n .with {\n $0.interface = name\n $0.address = address\n })\n }\n\n /// Set the default route in the sandbox's environment.\n public func routeAddDefault(name: String, gateway: String) async throws {\n _ = try await client.ipRouteAddDefault(\n .with {\n $0.interface = name\n $0.gateway = gateway\n })\n }\n\n /// Configure DNS within the sandbox's environment.\n public func configureDNS(config: DNS, location: String) async throws {\n _ = try await client.configureDns(\n .with {\n $0.location = location\n $0.nameservers = config.nameservers\n if let domain = config.domain {\n $0.domain = domain\n }\n $0.searchDomains = config.searchDomains\n $0.options = config.options\n })\n }\n\n /// Configure /etc/hosts within the sandbox's environment.\n public func configureHosts(config: Hosts, location: String) async throws {\n _ = try await client.configureHosts(config.toAgentHostsRequest(location: location))\n }\n\n /// Perform a sync call.\n public func sync() async throws {\n _ = try await client.sync(.init())\n }\n\n public func kill(pid: Int32, signal: Int32) async throws -> Int32 {\n let response = try await client.kill(\n .with {\n $0.pid = pid\n $0.signal = signal\n })\n return response.result\n }\n\n /// Syncing shutdown will send a SIGTERM to all processes\n /// and wait, perform a sync operation, then issue a SIGKILL\n /// to the remaining processes before syncing again.\n public func syncingShutdown() async throws {\n _ = try await self.kill(pid: -1, signal: SIGTERM)\n try await Task.sleep(for: .milliseconds(10))\n try await self.sync()\n\n _ = try await self.kill(pid: -1, signal: SIGKILL)\n try await Task.sleep(for: .milliseconds(10))\n try await self.sync()\n }\n}\n\nextension Hosts {\n func toAgentHostsRequest(location: String) -> Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest {\n Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.with {\n $0.location = location\n if let comment {\n $0.comment = comment\n }\n $0.entries = entries.map {\n let entry = $0\n return Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.HostsEntry.with {\n if let comment = entry.comment {\n $0.comment = comment\n }\n $0.ipAddress = entry.ipAddress\n $0.hostnames = entry.hostnames\n }\n }\n }\n }\n}\n\nextension Vminitd.Client {\n public init(socket: String, group: MultiThreadedEventLoopGroup) {\n var config = ClientConnection.Configuration.default(\n target: .unixDomainSocket(socket),\n eventLoopGroup: group\n )\n config.maximumReceiveMessageLength = Int(64.mib())\n config.connectionBackoff = ConnectionBackoff(retries: .upTo(5))\n\n self = .init(channel: ClientConnection(configuration: config))\n }\n\n public init(connection: FileHandle, group: MultiThreadedEventLoopGroup) {\n var config = ClientConnection.Configuration.default(\n target: .connectedSocket(connection.fileDescriptor),\n eventLoopGroup: group\n )\n config.maximumReceiveMessageLength = Int(64.mib())\n config.connectionBackoff = ConnectionBackoff(retries: .upTo(5))\n\n self = .init(channel: ClientConnection(configuration: config))\n }\n\n public func close() async throws {\n try await self.channel.close().get()\n }\n}\n"], ["/containerization/Sources/Containerization/LinuxProcess.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport Synchronization\n\n/// `LinuxProcess` represents a Linux process and is used to\n/// setup and control the full lifecycle for the process.\npublic final class LinuxProcess: Sendable {\n /// The ID of the process. This is purely metadata for the caller.\n public let id: String\n\n /// What container owns this process (if any).\n public let owningContainer: String?\n\n package struct StdioSetup: Sendable {\n let port: UInt32\n let writer: Writer\n }\n\n package struct StdioReaderSetup {\n let port: UInt32\n let reader: ReaderStream\n }\n\n package struct Stdio: Sendable {\n let stdin: StdioReaderSetup?\n let stdout: StdioSetup?\n let stderr: StdioSetup?\n }\n\n private struct StdioHandles: Sendable {\n var stdin: FileHandle?\n var stdout: FileHandle?\n var stderr: FileHandle?\n\n mutating func close() throws {\n if let stdin {\n try stdin.close()\n stdin.readabilityHandler = nil\n self.stdin = nil\n }\n if let stdout {\n try stdout.close()\n stdout.readabilityHandler = nil\n self.stdout = nil\n }\n if let stderr {\n try stderr.close()\n stderr.readabilityHandler = nil\n self.stderr = nil\n }\n }\n }\n\n private struct State {\n var spec: ContainerizationOCI.Spec\n var pid: Int32\n var stdio: StdioHandles\n var stdinRelay: Task<(), Never>?\n var ioTracker: IoTracker?\n\n struct IoTracker {\n let stream: AsyncStream\n let cont: AsyncStream.Continuation\n let configuredStreams: Int\n }\n }\n\n /// The process ID for the container process. This will be -1\n /// if the process has not been started.\n public var pid: Int32 {\n state.withLock { $0.pid }\n }\n\n private let state: Mutex\n private let ioSetup: Stdio\n private let agent: any VirtualMachineAgent\n private let vm: any VirtualMachineInstance\n private let logger: Logger?\n\n init(\n _ id: String,\n containerID: String? = nil,\n spec: Spec,\n io: Stdio,\n agent: any VirtualMachineAgent,\n vm: any VirtualMachineInstance,\n logger: Logger?\n ) {\n self.id = id\n self.owningContainer = containerID\n self.state = Mutex(.init(spec: spec, pid: -1, stdio: StdioHandles()))\n self.ioSetup = io\n self.agent = agent\n self.vm = vm\n self.logger = logger\n }\n}\n\nextension LinuxProcess {\n func setupIO(streams: [VsockConnectionStream?]) async throws -> [FileHandle?] {\n let handles = try await Timeout.run(seconds: 3) {\n await withTaskGroup(of: (Int, FileHandle?).self) { group in\n var results = [FileHandle?](repeating: nil, count: 3)\n\n for (index, stream) in streams.enumerated() {\n guard let stream = stream else { continue }\n\n group.addTask {\n let first = await stream.connections.first(where: { _ in true })\n return (index, first)\n }\n }\n\n for await (index, fileHandle) in group {\n results[index] = fileHandle\n }\n return results\n }\n }\n\n if let stdin = self.ioSetup.stdin {\n if let handle = handles[0] {\n self.state.withLock {\n $0.stdinRelay = Task {\n for await data in stdin.reader.stream() {\n do {\n try handle.write(contentsOf: data)\n } catch {\n self.logger?.error(\"failed to write to stdin: \\(error)\")\n break\n }\n }\n\n do {\n self.logger?.debug(\"stdin relay finished, closing\")\n\n // There's two ways we can wind up here:\n //\n // 1. The stream finished on its own (e.g. we wrote all the\n // data) and we will close the underlying stdin in the guest below.\n //\n // 2. The client explicitly called closeStdin() themselves\n // which will cancel this relay task AFTER actually closing\n // the fds. If the client did that, then this task will be\n // cancelled, and the fds are already gone so there's nothing\n // for us to do.\n if Task.isCancelled {\n return\n }\n\n try await self._closeStdin()\n } catch {\n self.logger?.error(\"failed to close stdin: \\(error)\")\n }\n }\n }\n }\n }\n\n var configuredStreams = 0\n let (stream, cc) = AsyncStream.makeStream()\n if let stdout = self.ioSetup.stdout {\n configuredStreams += 1\n handles[1]?.readabilityHandler = { handle in\n do {\n let data = handle.availableData\n if data.isEmpty {\n // This block is called when the producer (the guest) closes\n // the fd it is writing into.\n handles[1]?.readabilityHandler = nil\n cc.yield()\n return\n }\n try stdout.writer.write(data)\n } catch {\n self.logger?.error(\"failed to write to stdout: \\(error)\")\n }\n }\n }\n\n if let stderr = self.ioSetup.stderr {\n configuredStreams += 1\n handles[2]?.readabilityHandler = { handle in\n do {\n let data = handle.availableData\n if data.isEmpty {\n handles[2]?.readabilityHandler = nil\n cc.yield()\n return\n }\n try stderr.writer.write(data)\n } catch {\n self.logger?.error(\"failed to write to stderr: \\(error)\")\n }\n }\n }\n if configuredStreams > 0 {\n self.state.withLock {\n $0.ioTracker = .init(stream: stream, cont: cc, configuredStreams: configuredStreams)\n }\n }\n\n return handles\n }\n\n /// Start the process.\n public func start() async throws {\n do {\n let spec = self.state.withLock { $0.spec }\n var streams = [VsockConnectionStream?](repeating: nil, count: 3)\n if let stdin = self.ioSetup.stdin {\n streams[0] = try self.vm.listen(stdin.port)\n }\n if let stdout = self.ioSetup.stdout {\n streams[1] = try self.vm.listen(stdout.port)\n }\n if let stderr = self.ioSetup.stderr {\n if spec.process!.terminal {\n throw ContainerizationError(\n .invalidArgument,\n message: \"stderr should not be configured with terminal=true\"\n )\n }\n streams[2] = try self.vm.listen(stderr.port)\n }\n\n let t = Task {\n try await self.setupIO(streams: streams)\n }\n\n try await agent.createProcess(\n id: self.id,\n containerID: self.owningContainer,\n stdinPort: self.ioSetup.stdin?.port,\n stdoutPort: self.ioSetup.stdout?.port,\n stderrPort: self.ioSetup.stderr?.port,\n configuration: spec,\n options: nil\n )\n\n let result = try await t.value\n let pid = try await self.agent.startProcess(\n id: self.id,\n containerID: self.owningContainer\n )\n\n self.state.withLock {\n $0.stdio = StdioHandles(\n stdin: result[0],\n stdout: result[1],\n stderr: result[2]\n )\n $0.pid = pid\n }\n } catch {\n if let err = error as? ContainerizationError {\n throw err\n }\n throw ContainerizationError(\n .internalError,\n message: \"failed to start process\",\n cause: error,\n )\n }\n }\n\n /// Kill the process with the specified signal.\n public func kill(_ signal: Int32) async throws {\n do {\n try await agent.signalProcess(\n id: self.id,\n containerID: self.owningContainer,\n signal: signal\n )\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to kill process\",\n cause: error\n )\n }\n }\n\n /// Resize the processes pty (if requested).\n public func resize(to: Terminal.Size) async throws {\n do {\n try await agent.resizeProcess(\n id: self.id,\n containerID: self.owningContainer,\n columns: UInt32(to.width),\n rows: UInt32(to.height)\n )\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to resize process\",\n cause: error\n )\n }\n }\n\n public func closeStdin() async throws {\n do {\n try await self._closeStdin()\n self.state.withLock {\n $0.stdinRelay?.cancel()\n }\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to close stdin\",\n cause: error,\n )\n }\n }\n\n func _closeStdin() async throws {\n try await self.agent.closeProcessStdin(\n id: self.id,\n containerID: self.owningContainer\n )\n }\n\n /// Wait on the process to exit with an optional timeout. Returns the exit code of the process.\n @discardableResult\n public func wait(timeoutInSeconds: Int64? = nil) async throws -> Int32 {\n do {\n let code = try await self.agent.waitProcess(\n id: self.id,\n containerID: self.owningContainer,\n timeoutInSeconds: timeoutInSeconds\n )\n await self.waitIoComplete()\n return code\n } catch {\n if error is ContainerizationError {\n throw error\n }\n throw ContainerizationError(\n .internalError,\n message: \"failed to wait on process\",\n cause: error\n )\n }\n }\n\n /// Wait until the standard output and standard error streams for the process have concluded.\n private func waitIoComplete() async {\n let ioTracker = self.state.withLock { $0.ioTracker }\n guard let ioTracker else {\n return\n }\n do {\n try await Timeout.run(seconds: 3) {\n var counter = ioTracker.configuredStreams\n for await _ in ioTracker.stream {\n counter -= 1\n if counter == 0 {\n ioTracker.cont.finish()\n break\n }\n }\n }\n } catch {\n self.logger?.error(\"Timeout waiting for IO to complete for process \\(id): \\(error)\")\n }\n self.state.withLock {\n $0.ioTracker = nil\n }\n }\n\n /// Cleans up guest state and waits on and closes any host resources (stdio handles).\n public func delete() async throws {\n do {\n try await self.agent.deleteProcess(\n id: self.id,\n containerID: self.owningContainer\n )\n } catch {\n self.logger?.error(\n \"process deletion\",\n metadata: [\n \"id\": \"\\(self.id)\",\n \"error\": \"\\(error)\",\n ])\n }\n\n do {\n try self.state.withLock {\n $0.stdinRelay?.cancel()\n try $0.stdio.close()\n }\n } catch {\n self.logger?.error(\n \"closing process stdio\",\n metadata: [\n \"id\": \"\\(self.id)\",\n \"error\": \"\\(error)\",\n ])\n }\n\n do {\n try await self.agent.close()\n } catch {\n throw ContainerizationError(\n .internalError,\n message: \"failed to close agent connection\",\n cause: error,\n )\n }\n }\n}\n"], ["/containerization/Sources/Containerization/Mount.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport Virtualization\nimport ContainerizationError\n#endif\n\n/// A filesystem mount exposed to a container.\npublic struct Mount: Sendable {\n /// The filesystem or mount type. This is the string\n /// that will be used for the mount syscall itself.\n public var type: String\n /// The source path of the mount.\n public var source: String\n /// The destination path of the mount.\n public var destination: String\n /// Filesystem or mount specific options.\n public var options: [String]\n /// Runtime specific options. This can be used\n /// as a way to discern what kind of device a vmm\n /// should create for this specific mount (virtioblock\n /// virtiofs etc.).\n public let runtimeOptions: RuntimeOptions\n\n /// A type representing a \"hint\" of what type\n /// of mount this really is (block, directory, purely\n /// guest mount) and a set of type specific options, if any.\n public enum RuntimeOptions: Sendable {\n case virtioblk([String])\n case virtiofs([String])\n case any\n }\n\n init(\n type: String,\n source: String,\n destination: String,\n options: [String],\n runtimeOptions: RuntimeOptions\n ) {\n self.type = type\n self.source = source\n self.destination = destination\n self.options = options\n self.runtimeOptions = runtimeOptions\n }\n\n /// Mount representing a virtio block device.\n public static func block(\n format: String,\n source: String,\n destination: String,\n options: [String] = [],\n runtimeOptions: [String] = []\n ) -> Self {\n .init(\n type: format,\n source: source,\n destination: destination,\n options: options,\n runtimeOptions: .virtioblk(runtimeOptions)\n )\n }\n\n /// Mount representing a virtiofs share.\n public static func share(\n source: String,\n destination: String,\n options: [String] = [],\n runtimeOptions: [String] = []\n ) -> Self {\n .init(\n type: \"virtiofs\",\n source: source,\n destination: destination,\n options: options,\n runtimeOptions: .virtiofs(runtimeOptions)\n )\n }\n\n /// A generic mount.\n public static func any(\n type: String,\n source: String,\n destination: String,\n options: [String] = []\n ) -> Self {\n .init(\n type: type,\n source: source,\n destination: destination,\n options: options,\n runtimeOptions: .any\n )\n }\n\n #if os(macOS)\n /// Clone the Mount to the provided path.\n ///\n /// This uses `clonefile` to provide a copy-on-write copy of the Mount.\n public func clone(to: String) throws -> Self {\n let fm = FileManager.default\n let src = self.source\n try fm.copyItem(atPath: src, toPath: to)\n\n return .init(\n type: self.type,\n source: to,\n destination: self.destination,\n options: self.options,\n runtimeOptions: self.runtimeOptions\n )\n }\n #endif\n}\n\n#if os(macOS)\n\nextension Mount {\n func configure(config: inout VZVirtualMachineConfiguration) throws {\n switch self.runtimeOptions {\n case .virtioblk(let options):\n let device = try VZDiskImageStorageDeviceAttachment.mountToVZAttachment(mount: self, options: options)\n let attachment = VZVirtioBlockDeviceConfiguration(attachment: device)\n config.storageDevices.append(attachment)\n case .virtiofs(_):\n guard FileManager.default.fileExists(atPath: self.source) else {\n throw ContainerizationError(.notFound, message: \"directory \\(source) does not exist\")\n }\n\n let name = try hashMountSource(source: self.source)\n let urlSource = URL(fileURLWithPath: source)\n\n let device = VZVirtioFileSystemDeviceConfiguration(tag: name)\n device.share = VZSingleDirectoryShare(\n directory: VZSharedDirectory(\n url: urlSource,\n readOnly: readonly\n )\n )\n config.directorySharingDevices.append(device)\n case .any:\n break\n }\n }\n}\n\nextension VZDiskImageStorageDeviceAttachment {\n static func mountToVZAttachment(mount: Mount, options: [String]) throws -> VZDiskImageStorageDeviceAttachment {\n var cachingMode: VZDiskImageCachingMode = .automatic\n var synchronizationMode: VZDiskImageSynchronizationMode = .none\n\n for option in options {\n let split = option.split(separator: \"=\")\n if split.count != 2 {\n continue\n }\n\n let key = String(split[0])\n let value = String(split[1])\n\n switch key {\n case \"vzDiskImageCachingMode\":\n switch value {\n case \"automatic\":\n cachingMode = .automatic\n case \"cached\":\n cachingMode = .cached\n case \"uncached\":\n cachingMode = .uncached\n default:\n throw ContainerizationError(\n .invalidArgument,\n message: \"unknown vzDiskImageCachingMode value for virtio block device: \\(value)\"\n )\n }\n case \"vzDiskImageSynchronizationMode\":\n switch value {\n case \"full\":\n synchronizationMode = .full\n case \"fsync\":\n synchronizationMode = .fsync\n case \"none\":\n synchronizationMode = .none\n default:\n throw ContainerizationError(\n .invalidArgument,\n message: \"unknown vzDiskImageSynchronizationMode value for virtio block device: \\(value)\"\n )\n }\n default:\n throw ContainerizationError(\n .invalidArgument,\n message: \"unknown vmm option encountered: \\(key)\"\n )\n }\n }\n return try VZDiskImageStorageDeviceAttachment(\n url: URL(filePath: mount.source),\n readOnly: mount.readonly,\n cachingMode: cachingMode,\n synchronizationMode: synchronizationMode\n )\n }\n}\n\n#endif\n\nextension Mount {\n fileprivate var readonly: Bool {\n self.options.contains(\"ro\")\n }\n}\n"], ["/containerization/Sources/ContainerizationNetlink/NetlinkSession.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport ContainerizationOS\nimport Logging\n\n/// `NetlinkSession` facilitates interacting with netlink via a provided `NetlinkSocket`. This is the\n/// core high-level type offered to perform actions to the netlink surface in the kernel.\npublic struct NetlinkSession {\n private static let receiveDataLength = 65536\n private static let mtu: UInt32 = 1280\n private let socket: any NetlinkSocket\n private let log: Logger\n\n /// Creates a new `NetlinkSession`.\n /// - Parameters:\n /// - socket: The `NetlinkSocket` to use for netlink interaction.\n /// - log: The logger to use. The default value is `nil`.\n public init(socket: any NetlinkSocket, log: Logger? = nil) {\n self.socket = socket\n self.log = log ?? Logger(label: \"com.apple.containerization.netlink\")\n }\n\n /// Errors that may occur during netlink interaction.\n public enum Error: Swift.Error, CustomStringConvertible, Equatable {\n case invalidIpAddress\n case invalidPrefixLength\n case unexpectedInfo(type: UInt16)\n case unexpectedOffset(offset: Int, size: Int)\n case unexpectedResidualPackets\n case unexpectedResultSet(count: Int, expected: Int)\n\n /// The description of the errors.\n public var description: String {\n switch self {\n case .invalidIpAddress:\n return \"invalid IP address\"\n case .invalidPrefixLength:\n return \"invalid prefix length\"\n case .unexpectedInfo(let type):\n return \"unexpected response information, type = \\(type)\"\n case .unexpectedOffset(let offset, let size):\n return \"unexpected buffer state, offset = \\(offset), size = \\(size)\"\n case .unexpectedResidualPackets:\n return \"unexpected residual response packets\"\n case .unexpectedResultSet(let count, let expected):\n return \"unexpected result set size, count = \\(count), expected = \\(expected)\"\n }\n }\n }\n\n /// Performs a link set command on an interface.\n /// - Parameters:\n /// - interface: The name of the interface.\n /// - up: The value to set the interface state to.\n public func linkSet(interface: String, up: Bool, mtu: UInt32? = nil) throws {\n // ip link set dev [interface] [up|down]\n let interfaceIndex = try getInterfaceIndex(interface)\n // build the attribute only when mtu is supplied\n let attr: RTAttribute? =\n (mtu != nil)\n ? RTAttribute(\n len: UInt16(RTAttribute.size + MemoryLayout.size),\n type: LinkAttributeType.IFLA_MTU)\n : nil\n let requestSize = NetlinkMessageHeader.size + InterfaceInfo.size + (attr?.paddedLen ?? 0)\n var requestBuffer = [UInt8](repeating: 0, count: requestSize)\n var requestOffset = 0\n\n let requestHeader = NetlinkMessageHeader(\n len: UInt32(requestBuffer.count),\n type: NetlinkType.RTM_NEWLINK,\n flags: NetlinkFlags.NLM_F_REQUEST | NetlinkFlags.NLM_F_ACK,\n pid: socket.pid)\n requestOffset = try requestHeader.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let flags = up ? InterfaceFlags.IFF_UP : 0\n let requestInfo = InterfaceInfo(\n family: UInt8(AddressFamily.AF_PACKET),\n index: interfaceIndex,\n flags: flags,\n change: InterfaceFlags.DEFAULT_CHANGE)\n requestOffset = try requestInfo.appendBuffer(&requestBuffer, offset: requestOffset)\n\n if let attr = attr, let m = mtu {\n requestOffset = try attr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard\n let newRequestOffset =\n requestBuffer.copyIn(as: UInt32.self, value: m, offset: requestOffset)\n else {\n throw NetlinkDataError.sendMarshalFailure\n }\n requestOffset = newRequestOffset\n }\n\n guard requestOffset == requestSize else {\n throw Error.unexpectedOffset(offset: requestOffset, size: requestSize)\n }\n\n try sendRequest(buffer: &requestBuffer)\n let (infos, _) = try parseResponse(infoType: NetlinkType.RTM_NEWLINK) { InterfaceInfo() }\n guard infos.count == 0 else {\n throw Error.unexpectedResultSet(count: infos.count, expected: 0)\n }\n }\n\n /// Performs a link get command on an interface.\n /// Returns information about the interface.\n /// - Parameter interface: The name of the interface to query.\n public func linkGet(interface: String? = nil) throws -> [LinkResponse] {\n // ip link ip show\n let maskAttr = RTAttribute(\n len: UInt16(RTAttribute.size + MemoryLayout.size), type: LinkAttributeType.IFLA_EXT_MASK)\n let interfaceName = try interface.map { try getInterfaceName($0) }\n let interfaceNameAttr = interfaceName.map {\n RTAttribute(len: UInt16(RTAttribute.size + $0.count), type: LinkAttributeType.IFLA_EXT_IFNAME)\n }\n let requestSize =\n NetlinkMessageHeader.size + InterfaceInfo.size + maskAttr.paddedLen + (interfaceNameAttr?.paddedLen ?? 0)\n var requestBuffer = [UInt8](repeating: 0, count: requestSize)\n var requestOffset = 0\n\n let flags =\n interface != nil ? NetlinkFlags.NLM_F_REQUEST : (NetlinkFlags.NLM_F_REQUEST | NetlinkFlags.NLM_F_DUMP)\n let requestHeader = NetlinkMessageHeader(\n len: UInt32(requestBuffer.count),\n type: NetlinkType.RTM_GETLINK,\n flags: flags,\n pid: socket.pid)\n requestOffset = try requestHeader.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let requestInfo = InterfaceInfo(\n family: UInt8(AddressFamily.AF_PACKET),\n index: 0,\n flags: InterfaceFlags.IFF_UP,\n change: InterfaceFlags.DEFAULT_CHANGE)\n requestOffset = try requestInfo.appendBuffer(&requestBuffer, offset: requestOffset)\n\n requestOffset = try maskAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard\n var requestOffset = requestBuffer.copyIn(\n as: UInt32.self,\n value: LinkAttributeMaskFilter.RTEXT_FILTER_VF | LinkAttributeMaskFilter.RTEXT_FILTER_SKIP_STATS,\n offset: requestOffset)\n else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n if let interfaceNameAttr {\n if let interfaceName {\n requestOffset = try interfaceNameAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard let updatedRequestOffset = requestBuffer.copyIn(buffer: interfaceName, offset: requestOffset)\n else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n requestOffset = updatedRequestOffset\n }\n }\n\n guard requestOffset == requestSize else {\n throw Error.unexpectedOffset(offset: requestOffset, size: requestSize)\n }\n\n try sendRequest(buffer: &requestBuffer)\n let (infos, attrDataLists) = try parseResponse(infoType: NetlinkType.RTM_NEWLINK) { InterfaceInfo() }\n var linkResponses: [LinkResponse] = []\n for i in 0...size * ipAddressBytes.count\n let requestSize = NetlinkMessageHeader.size + AddressInfo.size + 2 * addressAttrSize\n var requestBuffer = [UInt8](repeating: 0, count: requestSize)\n var requestOffset = 0\n\n let header = NetlinkMessageHeader(\n len: UInt32(requestBuffer.count),\n type: NetlinkType.RTM_NEWADDR,\n flags: NetlinkFlags.NLM_F_REQUEST | NetlinkFlags.NLM_F_ACK | NetlinkFlags.NLM_F_EXCL\n | NetlinkFlags.NLM_F_CREATE,\n seq: 0,\n pid: socket.pid)\n requestOffset = try header.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let requestInfo = AddressInfo(\n family: UInt8(AddressFamily.AF_INET),\n prefixLength: parsed.prefix,\n flags: 0,\n scope: NetlinkScope.RT_SCOPE_UNIVERSE,\n index: UInt32(interfaceIndex))\n requestOffset = try requestInfo.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let ipLocalAttr = RTAttribute(len: UInt16(addressAttrSize), type: AddressAttributeType.IFA_LOCAL)\n requestOffset = try ipLocalAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard var requestOffset = requestBuffer.copyIn(buffer: ipAddressBytes, offset: requestOffset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n let ipAddressAttr = RTAttribute(len: UInt16(addressAttrSize), type: AddressAttributeType.IFA_ADDRESS)\n requestOffset = try ipAddressAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard let requestOffset = requestBuffer.copyIn(buffer: ipAddressBytes, offset: requestOffset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n guard requestOffset == requestSize else {\n throw Error.unexpectedOffset(offset: requestOffset, size: requestSize)\n }\n\n try sendRequest(buffer: &requestBuffer)\n let (infos, _) = try parseResponse(infoType: NetlinkType.RTM_NEWLINK) { AddressInfo() }\n guard infos.count == 0 else {\n throw Error.unexpectedResultSet(count: infos.count, expected: 0)\n }\n }\n\n private func parseCIDR(cidr: String) throws -> (address: String, prefix: UInt8) {\n let split = cidr.components(separatedBy: \"/\")\n guard split.count == 2 else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n let address = split[0]\n guard let prefixLength = PrefixLength(split[1]) else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n guard prefixLength >= 0 && prefixLength <= 32 else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n return (address, prefixLength)\n }\n\n /// Adds a route to an interface.\n /// - Parameters:\n /// - interface: The name of the interface.\n /// - destinationAddress: The destination address to route to.\n /// - srcAddr: The source address to route from.\n public func routeAdd(\n interface: String,\n destinationAddress: String,\n srcAddr: String\n ) throws {\n // ip route add [dest-cidr] dev [interface] src [src-addr] proto kernel\n let parsed = try parseCIDR(cidr: destinationAddress)\n let interfaceIndex = try getInterfaceIndex(interface)\n let dstAddrBytes = try IPv4Address(parsed.address).networkBytes\n let dstAddrAttrSize = RTAttribute.size + dstAddrBytes.count\n let srcAddrBytes = try IPv4Address(srcAddr).networkBytes\n let srcAddrAttrSize = RTAttribute.size + srcAddrBytes.count\n let interfaceAttrSize = RTAttribute.size + MemoryLayout.size\n let requestSize =\n NetlinkMessageHeader.size + RouteInfo.size + dstAddrAttrSize + srcAddrAttrSize + interfaceAttrSize\n var requestBuffer = [UInt8](repeating: 0, count: requestSize)\n var requestOffset = 0\n\n let header = NetlinkMessageHeader(\n len: UInt32(requestBuffer.count),\n type: NetlinkType.RTM_NEWROUTE,\n flags: NetlinkFlags.NLM_F_REQUEST | NetlinkFlags.NLM_F_ACK | NetlinkFlags.NLM_F_EXCL\n | NetlinkFlags.NLM_F_CREATE,\n pid: socket.pid)\n requestOffset = try header.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let requestInfo = RouteInfo(\n family: UInt8(AddressFamily.AF_INET),\n dstLen: parsed.prefix,\n srcLen: 0,\n tos: 0,\n table: RouteTable.MAIN,\n proto: RouteProtocol.KERNEL,\n scope: RouteScope.LINK,\n type: RouteType.UNICAST,\n flags: 0)\n requestOffset = try requestInfo.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let dstAddrAttr = RTAttribute(len: UInt16(dstAddrAttrSize), type: RouteAttributeType.DST)\n requestOffset = try dstAddrAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard var requestOffset = requestBuffer.copyIn(buffer: dstAddrBytes, offset: requestOffset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n let srcAddrAttr = RTAttribute(len: UInt16(dstAddrAttrSize), type: RouteAttributeType.PREFSRC)\n requestOffset = try srcAddrAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard var requestOffset = requestBuffer.copyIn(buffer: srcAddrBytes, offset: requestOffset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n let interfaceAttr = RTAttribute(len: UInt16(interfaceAttrSize), type: RouteAttributeType.OIF)\n requestOffset = try interfaceAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard\n let requestOffset = requestBuffer.copyIn(\n as: UInt32.self,\n value: UInt32(interfaceIndex),\n offset: requestOffset)\n else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n guard requestOffset == requestSize else {\n throw Error.unexpectedOffset(offset: requestOffset, size: requestSize)\n }\n\n try sendRequest(buffer: &requestBuffer)\n let (infos, _) = try parseResponse(infoType: NetlinkType.RTM_NEWLINK) { AddressInfo() }\n guard infos.count == 0 else {\n throw Error.unexpectedResultSet(count: infos.count, expected: 0)\n }\n }\n\n /// Adds a default route to an interface.\n /// - Parameters:\n /// - interface: The name of the interface.\n /// - gateway: The gateway address.\n public func routeAddDefault(\n interface: String,\n gateway: String\n ) throws {\n // ip route add default via [dst-address] src [src-address]\n let dstAddrBytes = try IPv4Address(gateway).networkBytes\n let dstAddrAttrSize = RTAttribute.size + dstAddrBytes.count\n\n let interfaceAttrSize = RTAttribute.size + MemoryLayout.size\n let interfaceIndex = try getInterfaceIndex(interface)\n let requestSize = NetlinkMessageHeader.size + RouteInfo.size + dstAddrAttrSize + interfaceAttrSize\n\n var requestBuffer = [UInt8](repeating: 0, count: requestSize)\n var requestOffset = 0\n\n let header = NetlinkMessageHeader(\n len: UInt32(requestBuffer.count),\n type: NetlinkType.RTM_NEWROUTE,\n flags: NetlinkFlags.NLM_F_REQUEST | NetlinkFlags.NLM_F_ACK | NetlinkFlags.NLM_F_EXCL\n | NetlinkFlags.NLM_F_CREATE,\n pid: socket.pid)\n requestOffset = try header.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let requestInfo = RouteInfo(\n family: UInt8(AddressFamily.AF_INET),\n dstLen: 0,\n srcLen: 0,\n tos: 0,\n table: RouteTable.MAIN,\n proto: RouteProtocol.BOOT,\n scope: RouteScope.UNIVERSE,\n type: RouteType.UNICAST,\n flags: 0)\n requestOffset = try requestInfo.appendBuffer(&requestBuffer, offset: requestOffset)\n\n let dstAddrAttr = RTAttribute(len: UInt16(dstAddrAttrSize), type: RouteAttributeType.GATEWAY)\n requestOffset = try dstAddrAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard var requestOffset = requestBuffer.copyIn(buffer: dstAddrBytes, offset: requestOffset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n let interfaceAttr = RTAttribute(len: UInt16(interfaceAttrSize), type: RouteAttributeType.OIF)\n requestOffset = try interfaceAttr.appendBuffer(&requestBuffer, offset: requestOffset)\n guard\n let requestOffset = requestBuffer.copyIn(\n as: UInt32.self,\n value: UInt32(interfaceIndex),\n offset: requestOffset)\n else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n guard requestOffset == requestSize else {\n throw Error.unexpectedOffset(offset: requestOffset, size: requestSize)\n }\n\n try sendRequest(buffer: &requestBuffer)\n let (infos, _) = try parseResponse(infoType: NetlinkType.RTM_NEWLINK) { AddressInfo() }\n guard infos.count == 0 else {\n throw Error.unexpectedResultSet(count: infos.count, expected: 0)\n }\n }\n\n private func getInterfaceName(_ interface: String) throws -> [UInt8] {\n guard let interfaceNameData = interface.data(using: .utf8) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n var interfaceName = [UInt8](interfaceNameData)\n interfaceName.append(0)\n\n while interfaceName.count % MemoryLayout.size != 0 {\n interfaceName.append(0)\n }\n\n return interfaceName\n }\n\n private func getInterfaceIndex(_ interface: String) throws -> Int32 {\n let linkResponses = try linkGet(interface: interface)\n guard linkResponses.count == 1 else {\n throw Error.unexpectedResultSet(count: linkResponses.count, expected: 1)\n }\n\n return linkResponses[0].interfaceIndex\n }\n\n private func sendRequest(buffer: inout [UInt8]) throws {\n log.trace(\"SEND-LENGTH: \\(buffer.count)\")\n log.trace(\"SEND-DUMP: \\(buffer[0.. ([UInt8], Int) {\n var buffer = [UInt8](repeating: 0, count: Self.receiveDataLength)\n let size = try socket.recv(buf: &buffer, len: Self.receiveDataLength, flags: 0)\n log.trace(\"RECV-LENGTH: \\(size)\")\n log.trace(\"RECV-DUMP: \\(buffer[0..(infoType: UInt16? = nil, _ infoProvider: () -> T) throws -> (\n [T], [[RTAttributeData]]\n ) {\n var infos: [T] = []\n var attrDataLists: [[RTAttributeData]] = []\n\n var moreResponses = false\n repeat {\n var (buffer, size) = try receiveResponse()\n let header: NetlinkMessageHeader\n var offset = 0\n\n (header, offset) = try parseHeader(buffer: &buffer, offset: offset)\n if let infoType {\n if header.type == infoType {\n log.trace(\n \"RECV-INFO-DUMP: dump = \\(buffer[offset.. (Int32, Int) {\n guard let errorPtr = buffer.bind(as: Int32.self, offset: offset) else {\n throw NetlinkDataError.recvUnmarshalFailure\n }\n\n let rc = errorPtr.pointee\n log.trace(\"RECV-ERR-CODE: \\(rc)\")\n\n return (rc, offset + MemoryLayout.size)\n }\n\n private func parseErrorResponse(buffer: inout [UInt8], offset: Int) throws -> Int {\n var (rc, offset) = try parseErrorCode(buffer: &buffer, offset: offset)\n log.trace(\n \"RECV-ERR-HEADER-DUMP: dump = \\(buffer[offset.. (NetlinkMessageHeader, Int) {\n log.trace(\"RECV-HEADER-DUMP: dump = \\(buffer[offset.. (\n [RTAttributeData], Int\n ) {\n var attrDatas: [RTAttributeData] = []\n var offset = offset\n var residualCount = residualCount\n log.trace(\"RECV-RESIDUAL: \\(residualCount)\")\n\n while residualCount > 0 {\n var attr = RTAttribute()\n log.trace(\" RECV-ATTR-DUMP: dump = \\(buffer[offset..= 0 {\n log.trace(\" RECV-ATTR-DATA-DUMP: dump = \\(buffer[offset.. 0 {\n config.dns = .init(nameservers: nameservers)\n }\n hosts.entries.append(\n Hosts.Entry(\n ipAddress: ip,\n hostnames: [id]\n ))\n }\n config.hosts = hosts\n }\n\n defer {\n try? manager.delete(id)\n }\n\n try await container.create()\n try await container.start()\n\n // Resize the containers pty to the current terminal window.\n try? await container.resize(to: try current.size)\n\n try await withThrowingTaskGroup(of: Void.self) { group in\n group.addTask {\n for await _ in sigwinchStream.signals {\n try await container.resize(to: try current.size)\n }\n }\n\n try await container.wait()\n group.cancelAll()\n\n try await container.stop()\n }\n }\n\n private static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.containerization\")\n }()\n }\n}\n"], ["/containerization/Sources/Containerization/Interface.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A network interface.\npublic protocol Interface: Sendable {\n /// The interface IPv4 address and subnet prefix length, as a CIDR address.\n /// Example: `192.168.64.3/24`\n var address: String { get }\n\n /// The IP address for the default route, or nil for no default route.\n var gateway: String? { get }\n\n /// The interface MAC address, or nil to auto-configure the address.\n var macAddress: String? { get }\n}\n"], ["/containerization/vminitd/Sources/vminitd/Server+GRPC.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport ContainerizationNetlink\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport GRPC\nimport Logging\nimport NIOCore\nimport NIOPosix\nimport _NIOFileSystem\n\nprivate let _setenv = Foundation.setenv\n\n#if canImport(Musl)\nimport Musl\nprivate let _mount = Musl.mount\nprivate let _umount = Musl.umount2\nprivate let _kill = Musl.kill\nprivate let _sync = Musl.sync\n#elseif canImport(Glibc)\nimport Glibc\nprivate let _mount = Glibc.mount\nprivate let _umount = Glibc.umount2\nprivate let _kill = Glibc.kill\nprivate let _sync = Glibc.sync\n#endif\n\nextension Initd: Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncProvider {\n func setTime(\n request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetTimeResponse {\n log.debug(\n \"setTime\",\n metadata: [\n \"sec\": \"\\(request.sec)\",\n \"usec\": \"\\(request.usec)\",\n ])\n\n var tv = timeval(tv_sec: time_t(request.sec), tv_usec: suseconds_t(request.usec))\n guard settimeofday(&tv, nil) == 0 else {\n let error = swiftErrno(\"settimeofday\")\n log.error(\n \"setTime\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"failed to settimeofday: \\(error)\")\n }\n\n return .init()\n }\n\n func setupEmulator(\n request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse {\n log.debug(\n \"setupEmulator\",\n metadata: [\n \"request\": \"\\(request)\"\n ])\n\n if !Binfmt.mounted() {\n throw GRPCStatus(\n code: .internalError,\n message: \"\\(Binfmt.path) is not mounted\"\n )\n }\n\n do {\n let bfmt = Binfmt.Entry(\n name: request.name,\n type: request.type,\n offset: request.offset,\n magic: request.magic,\n mask: request.mask,\n flags: request.flags\n )\n try bfmt.register(binaryPath: request.binaryPath)\n } catch {\n log.error(\n \"setupEmulator\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"setupEmulator: failed to register binfmt_misc entry: \\(error)\"\n )\n }\n\n return .init()\n }\n\n func sysctl(\n request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SysctlResponse {\n log.debug(\n \"sysctl\",\n metadata: [\n \"settings\": \"\\(request.settings)\"\n ])\n\n do {\n let sysctlPath = URL(fileURLWithPath: \"/proc/sys/\")\n for (k, v) in request.settings {\n guard let data = v.data(using: .ascii) else {\n throw GRPCStatus(code: .internalError, message: \"failed to convert \\(v) to data buffer for sysctl write\")\n }\n\n let setting =\n sysctlPath\n .appendingPathComponent(k.replacingOccurrences(of: \".\", with: \"/\"))\n let fh = try FileHandle(forWritingTo: setting)\n defer { try? fh.close() }\n\n try fh.write(contentsOf: data)\n }\n } catch {\n log.error(\n \"sysctl\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"sysctl: failed to set sysctl: \\(error)\"\n )\n }\n\n return .init()\n }\n\n func proxyVsock(\n request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse {\n log.debug(\n \"proxyVsock\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"port\": \"\\(request.vsockPort)\",\n \"guestPath\": \"\\(request.guestPath)\",\n \"action\": \"\\(request.action)\",\n ])\n\n do {\n let proxy = VsockProxy(\n id: request.id,\n action: request.action == .into ? .dial : .listen,\n port: request.vsockPort,\n path: URL(fileURLWithPath: request.guestPath),\n udsPerms: request.guestSocketPermissions,\n log: log\n )\n\n try proxy.start()\n try await state.add(proxy: proxy)\n } catch {\n log.error(\n \"proxyVsock\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"proxyVsock: failed to setup vsock proxy: \\(error)\"\n )\n }\n\n return .init()\n }\n\n func stopVsockProxy(\n request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse {\n log.debug(\n \"stopVsockProxy\",\n metadata: [\n \"id\": \"\\(request.id)\"\n ])\n\n do {\n let proxy = try await state.remove(proxy: request.id)\n try proxy.close()\n } catch {\n log.error(\n \"stopVsockProxy\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"stopVsockProxy: failed to stop vsock proxy: \\(error)\"\n )\n }\n\n return .init()\n }\n\n func mkdir(request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest, context: GRPC.GRPCAsyncServerCallContext)\n async throws -> Com_Apple_Containerization_Sandbox_V3_MkdirResponse\n {\n log.debug(\n \"mkdir\",\n metadata: [\n \"path\": \"\\(request.path)\",\n \"all\": \"\\(request.all)\",\n ])\n\n do {\n try FileManager.default.createDirectory(\n atPath: request.path,\n withIntermediateDirectories: request.all\n )\n } catch {\n log.error(\n \"mkdir\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"mkdir: \\(error)\")\n }\n\n return .init()\n }\n\n func mount(request: Com_Apple_Containerization_Sandbox_V3_MountRequest, context: GRPC.GRPCAsyncServerCallContext)\n async throws -> Com_Apple_Containerization_Sandbox_V3_MountResponse\n {\n log.debug(\n \"mount\",\n metadata: [\n \"type\": \"\\(request.type)\",\n \"source\": \"\\(request.source)\",\n \"destination\": \"\\(request.destination)\",\n ])\n\n do {\n let mnt = ContainerizationOS.Mount(\n type: request.type,\n source: request.source,\n target: request.destination,\n options: request.options\n )\n\n #if os(Linux)\n try mnt.mount(createWithPerms: 0o755)\n return .init()\n #else\n fatalError(\"mount not supported on platform\")\n #endif\n } catch {\n log.error(\n \"mount\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"mount: \\(error)\")\n }\n }\n\n func umount(request: Com_Apple_Containerization_Sandbox_V3_UmountRequest, context: GRPC.GRPCAsyncServerCallContext)\n async throws -> Com_Apple_Containerization_Sandbox_V3_UmountResponse\n {\n log.debug(\n \"umount\",\n metadata: [\n \"path\": \"\\(request.path)\",\n \"flags\": \"\\(request.flags)\",\n ])\n\n #if os(Linux)\n // Best effort EBUSY handle.\n for _ in 0...50 {\n let result = _umount(request.path, request.flags)\n if result == -1 {\n if errno == EBUSY {\n try await Task.sleep(for: .milliseconds(10))\n continue\n }\n let error = swiftErrno(\"umount\")\n\n log.error(\n \"umount\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .invalidArgument, message: \"umount: \\(error)\")\n }\n break\n }\n return .init()\n #else\n fatalError(\"umount not supported on platform\")\n #endif\n }\n\n func setenv(request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest, context: GRPC.GRPCAsyncServerCallContext)\n async throws -> Com_Apple_Containerization_Sandbox_V3_SetenvResponse\n {\n log.debug(\n \"setenv\",\n metadata: [\n \"key\": \"\\(request.key)\",\n \"value\": \"\\(request.value)\",\n ])\n\n guard _setenv(request.key, request.value, 1) == 0 else {\n let error = swiftErrno(\"setenv\")\n\n log.error(\n \"setEnv\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n\n throw GRPCStatus(code: .invalidArgument, message: \"setenv: \\(error)\")\n }\n return .init()\n }\n\n func getenv(request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest, context: GRPC.GRPCAsyncServerCallContext)\n async throws -> Com_Apple_Containerization_Sandbox_V3_GetenvResponse\n {\n log.debug(\n \"getenv\",\n metadata: [\n \"key\": \"\\(request.key)\"\n ])\n\n let env = ProcessInfo.processInfo.environment[request.key]\n return .with {\n if let env {\n $0.value = env\n }\n }\n }\n\n func createProcess(\n request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest, context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse {\n log.debug(\n \"createProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"stdin\": \"Port: \\(request.stdin)\",\n \"stdout\": \"Port: \\(request.stdout)\",\n \"stderr\": \"Port: \\(request.stderr)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n do {\n var ociSpec = try JSONDecoder().decode(\n ContainerizationOCI.Spec.self,\n from: request.configuration\n )\n\n try ociAlterations(ociSpec: &ociSpec)\n\n guard let process = ociSpec.process else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"oci runtime spec missing process configuration\"\n )\n }\n\n let stdioPorts = HostStdio(\n stdin: request.hasStdin ? request.stdin : nil,\n stdout: request.hasStdout ? request.stdout : nil,\n stderr: request.hasStderr ? request.stderr : nil,\n terminal: process.terminal\n )\n\n // This is an exec.\n if let container = await self.state.containers[request.containerID] {\n try await container.createExec(\n id: request.id,\n stdio: stdioPorts,\n process: process\n )\n } else {\n // We need to make our new fangled container.\n // The process ID must match the container ID for this.\n guard request.id == request.containerID else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"init process id must match container id\"\n )\n }\n\n // Write the etc/hostname file in the container rootfs since some init-systems\n // depend on it.\n let hostname = ociSpec.hostname\n if let root = ociSpec.root, !hostname.isEmpty {\n let etc = URL(fileURLWithPath: root.path).appendingPathComponent(\"etc\")\n try FileManager.default.createDirectory(atPath: etc.path, withIntermediateDirectories: true)\n let hostnamePath = etc.appendingPathComponent(\"hostname\")\n try hostname.write(toFile: hostnamePath.path, atomically: true, encoding: .utf8)\n }\n\n let ctr = try ManagedContainer(\n id: request.id,\n stdio: stdioPorts,\n spec: ociSpec,\n log: self.log\n )\n try await self.state.add(container: ctr)\n }\n\n return .init()\n } catch {\n log.error(\n \"createProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"error\": \"\\(error)\",\n ])\n if error is GRPCStatus {\n throw error\n }\n throw GRPCStatus(code: .internalError, message: \"create managed process: \\(error)\")\n }\n }\n\n func killProcess(\n request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillProcessResponse {\n log.debug(\n \"killProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"signal\": \"\\(request.signal)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n let ctr = try await self.state.get(container: request.containerID)\n try await ctr.kill(execID: request.id, request.signal)\n\n return .init()\n }\n\n func deleteProcess(\n request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest, context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse {\n log.debug(\n \"deleteProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n let ctr = try await self.state.get(container: request.containerID)\n\n // Are we trying to delete the container itself?\n if request.id == request.containerID {\n try await ctr.delete()\n try await state.remove(container: request.id)\n } else {\n // Or just a single exec.\n try await ctr.deleteExec(id: request.id)\n }\n\n return .init()\n }\n\n func startProcess(\n request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest, context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StartProcessResponse {\n log.debug(\n \"startProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n do {\n let ctr = try await self.state.get(container: request.containerID)\n let pid = try await ctr.start(execID: request.id)\n\n return .with {\n $0.pid = pid\n }\n } catch {\n log.error(\n \"startProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"error\": \"\\(error)\",\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"startProcess: failed to start process: \\(error)\"\n )\n }\n }\n\n func resizeProcess(\n request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest, context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse {\n log.debug(\n \"resizeProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n do {\n let ctr = try await self.state.get(container: request.containerID)\n let size = Terminal.Size(\n width: UInt16(request.columns),\n height: UInt16(request.rows)\n )\n try await ctr.resize(execID: request.id, size: size)\n } catch {\n log.error(\n \"resizeProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"error\": \"\\(error)\",\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"resizeProcess: failed to resize process: \\(error)\"\n )\n }\n\n return .init()\n }\n\n func waitProcess(\n request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest, context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse {\n log.debug(\n \"waitProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n do {\n let ctr = try await self.state.get(container: request.containerID)\n\n let exitCode = try await ctr.wait(execID: request.id)\n\n return .with {\n $0.exitCode = exitCode\n }\n } catch {\n log.error(\n \"waitProcess\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"error\": \"\\(error)\",\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"waitProcess: failed to wait on process: \\(error)\"\n )\n }\n }\n\n func closeProcessStdin(\n request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest, context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse {\n log.debug(\n \"closeProcessStdin\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n ])\n\n if !request.hasContainerID {\n fatalError(\"processes in the root of the vm not implemented\")\n }\n\n do {\n let ctr = try await self.state.get(container: request.containerID)\n\n try await ctr.closeStdin(execID: request.id)\n\n return .init()\n } catch {\n log.error(\n \"closeProcessStdin\",\n metadata: [\n \"id\": \"\\(request.id)\",\n \"containerID\": \"\\(request.containerID)\",\n \"error\": \"\\(error)\",\n ])\n throw GRPCStatus(\n code: .internalError,\n message: \"closeProcessStdin: failed to close process stdin: \\(error)\"\n )\n }\n }\n\n func ipLinkSet(\n request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest, context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse {\n log.debug(\n \"ip-link-set\",\n metadata: [\n \"interface\": \"\\(request.interface)\",\n \"up\": \"\\(request.up)\",\n ])\n\n do {\n let socket = try DefaultNetlinkSocket()\n let session = NetlinkSession(socket: socket, log: log)\n let mtuValue: UInt32? = request.hasMtu ? request.mtu : nil\n try session.linkSet(interface: request.interface, up: request.up, mtu: mtuValue)\n } catch {\n log.error(\n \"ip-link-set\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"ip-link-set: \\(error)\")\n }\n\n return .init()\n }\n\n func ipAddrAdd(\n request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest, context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse {\n log.debug(\n \"ip-addr-add\",\n metadata: [\n \"interface\": \"\\(request.interface)\",\n \"addr\": \"\\(request.address)\",\n ])\n\n do {\n let socket = try DefaultNetlinkSocket()\n let session = NetlinkSession(socket: socket, log: log)\n try session.addressAdd(interface: request.interface, address: request.address)\n } catch {\n log.error(\n \"ip-addr-add\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"ip-addr-add: \\(error)\")\n }\n\n return .init()\n }\n\n func ipRouteAddLink(\n request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest, context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse {\n log.debug(\n \"ip-route-add-link\",\n metadata: [\n \"interface\": \"\\(request.interface)\",\n \"address\": \"\\(request.address)\",\n \"srcAddr\": \"\\(request.srcAddr)\",\n ])\n\n do {\n let socket = try DefaultNetlinkSocket()\n let session = NetlinkSession(socket: socket, log: log)\n try session.routeAdd(\n interface: request.interface,\n destinationAddress: request.address,\n srcAddr: request.srcAddr\n )\n } catch {\n log.error(\n \"ip-route-add-link\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"ip-route-add-link: \\(error)\")\n }\n\n return .init()\n }\n\n func ipRouteAddDefault(\n request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse {\n log.debug(\n \"ip-route-add-default\",\n metadata: [\n \"interface\": \"\\(request.interface)\",\n \"gateway\": \"\\(request.gateway)\",\n ])\n\n do {\n let socket = try DefaultNetlinkSocket()\n let session = NetlinkSession(socket: socket, log: log)\n try session.routeAddDefault(interface: request.interface, gateway: request.gateway)\n } catch {\n log.error(\n \"ip-route-add-default\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"ip-route-add-default: \\(error)\")\n }\n\n return .init()\n }\n\n func configureDns(\n request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse {\n let domain = request.hasDomain ? request.domain : nil\n log.debug(\n \"configure-dns\",\n metadata: [\n \"location\": \"\\(request.location)\",\n \"nameservers\": \"\\(request.nameservers)\",\n \"domain\": \"\\(domain ?? \"\")\",\n ])\n\n do {\n let etc = URL(fileURLWithPath: request.location).appendingPathComponent(\"etc\")\n try FileManager.default.createDirectory(atPath: etc.path, withIntermediateDirectories: true)\n let resolvConf = etc.appendingPathComponent(\"resolv.conf\")\n let config = DNS(\n nameservers: request.nameservers,\n domain: domain,\n searchDomains: request.searchDomains,\n options: request.options\n )\n let text = config.resolvConf\n log.debug(\"writing to path \\(resolvConf.path) \\(text)\")\n try text.write(toFile: resolvConf.path, atomically: true, encoding: .utf8)\n log.debug(\"wrote resolver configuration\", metadata: [\"path\": \"\\(resolvConf.path)\"])\n } catch {\n log.error(\n \"configure-dns\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"configure-dns: \\(error)\")\n }\n\n return .init()\n }\n\n func configureHosts(\n request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse {\n log.debug(\n \"configureHosts\",\n metadata: [\n \"location\": \"\\(request.location)\"\n ])\n\n do {\n let etc = URL(fileURLWithPath: request.location).appendingPathComponent(\"etc\")\n try FileManager.default.createDirectory(atPath: etc.path, withIntermediateDirectories: true)\n let hostsPath = etc.appendingPathComponent(\"hosts\")\n\n let config = request.toCZHosts()\n let text = config.hostsFile\n try text.write(toFile: hostsPath.path, atomically: true, encoding: .utf8)\n\n log.debug(\"wrote /etc/hosts configuration\", metadata: [\"path\": \"\\(hostsPath.path)\"])\n } catch {\n log.error(\n \"configureHosts\",\n metadata: [\n \"error\": \"\\(error)\"\n ])\n throw GRPCStatus(code: .internalError, message: \"configureHosts: \\(error)\")\n }\n\n return .init()\n }\n\n private func swiftErrno(_ msg: Logger.Message) -> POSIXError {\n let error = POSIXError(.init(rawValue: errno)!)\n log.error(\n msg,\n metadata: [\n \"error\": \"\\(error)\"\n ])\n return error\n }\n\n func sync(\n request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n context: GRPC.GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SyncResponse {\n log.debug(\"sync\")\n\n _sync()\n return .init()\n }\n\n func kill(\n request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillResponse {\n log.debug(\n \"kill\",\n metadata: [\n \"pid\": \"\\(request.pid)\",\n \"signal\": \"\\(request.signal)\",\n ])\n\n let r = _kill(request.pid, request.signal)\n return .with {\n $0.result = r\n }\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest {\n func toCZHosts() -> Hosts {\n let entries = self.entries.map {\n Hosts.Entry(\n ipAddress: $0.ipAddress,\n hostnames: $0.hostnames,\n comment: $0.hasComment ? $0.comment : nil\n )\n }\n return Hosts(\n entries: entries,\n comment: self.hasComment ? self.comment : nil\n )\n }\n}\n\nextension Initd {\n func ociAlterations(ociSpec: inout ContainerizationOCI.Spec) throws {\n guard var process = ociSpec.process else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"runtime spec without process field present\"\n )\n }\n guard let root = ociSpec.root else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"runtime spec without root field present\"\n )\n }\n\n if process.cwd.isEmpty {\n process.cwd = \"/\"\n }\n\n // Username is truthfully a Windows field, but we use this as away to pass through\n // the exact string representation of a username a client may have given us.\n let username = process.user.username.isEmpty ? \"\\(process.user.uid):\\(process.user.gid)\" : process.user.username\n let parsedUser = try User.parseUser(root: root.path, userString: username)\n process.user.uid = parsedUser.uid\n process.user.gid = parsedUser.gid\n process.user.additionalGids = parsedUser.sgids\n if !process.env.contains(where: { $0.hasPrefix(\"HOME=\") }) {\n process.env.append(\"HOME=\\(parsedUser.home)\")\n }\n\n // Defensive programming a tad, but ensure we have TERM set if\n // the client requested a pty.\n if process.terminal {\n let termEnv = \"TERM=\"\n if !process.env.contains(where: { $0.hasPrefix(termEnv) }) {\n process.env.append(\"TERM=xterm\")\n }\n }\n\n ociSpec.process = process\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/NetworkAddress.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Errors related to IP and CIDR addresses.\npublic enum NetworkAddressError: Swift.Error, Equatable, CustomStringConvertible {\n case invalidStringAddress(address: String)\n case invalidNetworkByteAddress(address: [UInt8])\n case invalidCIDR(cidr: String)\n case invalidAddressForSubnet(address: String, cidr: String)\n case invalidAddressRange(lower: String, upper: String)\n\n public var description: String {\n switch self {\n case .invalidStringAddress(let address):\n return \"invalid IP address string \\(address)\"\n case .invalidNetworkByteAddress(let address):\n return \"invalid IP address bytes \\(address)\"\n case .invalidCIDR(let cidr):\n return \"invalid CIDR block: \\(cidr)\"\n case .invalidAddressForSubnet(let address, let cidr):\n return \"invalid address \\(address) for subnet \\(cidr)\"\n case .invalidAddressRange(let lower, let upper):\n return \"invalid range for addresses \\(lower) and \\(upper)\"\n }\n }\n}\n\npublic typealias PrefixLength = UInt8\n\nextension PrefixLength {\n /// Compute a bit mask that passes the suffix bits, given the network prefix mask length.\n public var suffixMask32: UInt32 {\n if self <= 0 {\n return 0xffff_ffff\n }\n return self >= 32 ? 0x0000_0000 : (1 << (32 - self)) - 1\n }\n\n /// Compute a bit mask that passes the prefix bits, given the network prefix mask length.\n public var prefixMask32: UInt32 {\n ~self.suffixMask32\n }\n\n /// Compute a bit mask that passes the suffix bits, given the network prefix mask length.\n public var suffixMask48: UInt64 {\n if self <= 0 {\n return 0x0000_ffff_ffff_ffff\n }\n return self >= 48 ? 0x0000_0000_0000_0000 : (1 << (48 - self)) - 1\n }\n\n /// Compute a bit mask that passes the prefix bits, given the network prefix mask length.\n public var prefixMask48: UInt64 {\n ~self.suffixMask48 & 0x0000_ffff_ffff_ffff\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/TerminalIO.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport Synchronization\n\nfinal class TerminalIO: ManagedProcess.IO & Sendable {\n private struct State {\n var stdin: IOPair?\n var stdout: IOPair?\n }\n\n private let parent: Terminal\n private let child: Terminal\n private let log: Logger?\n private let hostStdio: HostStdio\n private let state: Mutex\n\n init(\n stdio: HostStdio,\n log: Logger?\n ) throws {\n let pair = try Terminal.create()\n self.parent = pair.parent\n self.child = pair.child\n self.state = Mutex(State())\n self.hostStdio = stdio\n self.log = log\n }\n\n func resize(size: Terminal.Size) throws {\n try parent.resize(size: size)\n }\n\n func start(process: inout Command) throws {\n try self.state.withLock {\n let ptyHandle = self.child.handle\n let useHandles = self.hostStdio.stdin != nil || self.hostStdio.stdout != nil\n // We currently set stdin to the controlling terminal always, so\n // it must be a valid pty descriptor.\n process.stdin = useHandles ? ptyHandle : nil\n\n let stdoutHandle = useHandles ? ptyHandle : nil\n process.stdout = stdoutHandle\n process.stderr = stdoutHandle\n\n if let stdinPort = self.hostStdio.stdin {\n let type = VsockType(\n port: stdinPort,\n cid: VsockType.hostCID\n )\n let stdinSocket = try Socket(type: type, closeOnDeinit: false)\n try stdinSocket.connect()\n\n let pair = IOPair(\n readFrom: stdinSocket,\n writeTo: self.parent.handle,\n logger: self.log\n )\n $0.stdin = pair\n\n try pair.relay()\n }\n\n if let stdoutPort = self.hostStdio.stdout {\n let type = VsockType(\n port: stdoutPort,\n cid: VsockType.hostCID\n )\n let stdoutSocket = try Socket(type: type, closeOnDeinit: false)\n try stdoutSocket.connect()\n\n let pair = IOPair(\n readFrom: self.parent.handle,\n writeTo: stdoutSocket,\n logger: self.log\n )\n $0.stdout = pair\n\n try pair.relay()\n }\n }\n }\n\n func closeStdin() throws {\n self.state.withLock {\n $0.stdin?.close()\n }\n }\n\n func closeAfterExec() throws {\n try child.close()\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/StandardIO.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport Synchronization\n\nfinal class StandardIO: ManagedProcess.IO & Sendable {\n private struct State {\n var stdin: IOPair?\n var stdout: IOPair?\n var stderr: IOPair?\n\n var stdinPipe: Pipe?\n var stdoutPipe: Pipe?\n var stderrPipe: Pipe?\n }\n\n private let log: Logger?\n private let hostStdio: HostStdio\n private let state: Mutex\n\n init(\n stdio: HostStdio,\n log: Logger?\n ) {\n self.hostStdio = stdio\n self.log = log\n self.state = Mutex(State())\n }\n\n func start(process: inout Command) throws {\n try self.state.withLock {\n if let stdinPort = self.hostStdio.stdin {\n let inPipe = Pipe()\n process.stdin = inPipe.fileHandleForReading\n $0.stdinPipe = inPipe\n\n let type = VsockType(\n port: stdinPort,\n cid: VsockType.hostCID\n )\n let stdinSocket = try Socket(type: type, closeOnDeinit: false)\n try stdinSocket.connect()\n\n let pair = IOPair(\n readFrom: stdinSocket,\n writeTo: inPipe.fileHandleForWriting,\n logger: log\n )\n $0.stdin = pair\n\n try pair.relay()\n }\n\n if let stdoutPort = self.hostStdio.stdout {\n let outPipe = Pipe()\n process.stdout = outPipe.fileHandleForWriting\n $0.stdoutPipe = outPipe\n\n let type = VsockType(\n port: stdoutPort,\n cid: VsockType.hostCID\n )\n let stdoutSocket = try Socket(type: type, closeOnDeinit: false)\n try stdoutSocket.connect()\n\n let pair = IOPair(\n readFrom: outPipe.fileHandleForReading,\n writeTo: stdoutSocket,\n logger: log\n )\n $0.stdout = pair\n\n try pair.relay()\n }\n\n if let stderrPort = self.hostStdio.stderr {\n let errPipe = Pipe()\n process.stderr = errPipe.fileHandleForWriting\n $0.stderrPipe = errPipe\n\n let type = VsockType(\n port: stderrPort,\n cid: VsockType.hostCID\n )\n let stderrSocket = try Socket(type: type, closeOnDeinit: false)\n try stderrSocket.connect()\n\n let pair = IOPair(\n readFrom: errPipe.fileHandleForReading,\n writeTo: stderrSocket,\n logger: log\n )\n $0.stderr = pair\n\n try pair.relay()\n }\n }\n }\n\n // NOP\n func resize(size: Terminal.Size) throws {}\n\n func closeStdin() throws {\n self.state.withLock {\n if let stdin = $0.stdin {\n stdin.close()\n $0.stdin = nil\n }\n }\n }\n\n func closeAfterExec() throws {\n try self.state.withLock {\n if let stdin = $0.stdinPipe {\n try stdin.fileHandleForReading.close()\n }\n if let stdout = $0.stdoutPipe {\n try stdout.fileHandleForWriting.close()\n }\n if let stderr = $0.stderrPipe {\n try stderr.fileHandleForWriting.close()\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/AsyncSignalHandler.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Synchronization\n\n/// Async friendly wrapper around `DispatchSourceSignal`. Provides an `AsyncStream`\n/// interface to get notified of received signals.\npublic final class AsyncSignalHandler: Sendable {\n /// An async stream that returns the signal that was caught, if ever.\n public var signals: AsyncStream {\n let (stream, cont) = AsyncStream.makeStream(of: Int32.self)\n self.state.withLock {\n $0.conts.append(cont)\n }\n cont.onTermination = { @Sendable _ in\n self.cancel()\n }\n return stream\n }\n\n /// Cancel every AsyncStream of signals, as well as the underlying\n /// DispatchSignalSource's for each registered signal.\n public func cancel() {\n self.state.withLock {\n if $0.conts.isEmpty {\n return\n }\n\n for cont in $0.conts {\n cont.finish()\n }\n for source in $0.sources {\n source.cancel()\n }\n $0.conts.removeAll()\n $0.sources.removeAll()\n }\n }\n\n struct State: Sendable {\n var conts: [AsyncStream.Continuation] = []\n nonisolated(unsafe) var sources: [any DispatchSourceSignal] = []\n }\n\n // We keep a reference to the continuation object that is created for\n // our AsyncStream and tell our signal handler to yield a value to it\n // returning a value to the consumer\n private func handler(_ sig: Int32) {\n self.state.withLock {\n for cont in $0.conts {\n cont.yield(sig)\n }\n }\n }\n\n private let state: Mutex = .init(State())\n\n /// Create a new `AsyncSignalHandler` for the list of given signals `notify`.\n /// The default signal handlers for these signals are removed and async handlers\n /// added in their place. The async signal handlers that are installed simply\n /// yield to a stream if and when a signal is caught.\n public static func create(notify on: [Int32]) -> AsyncSignalHandler {\n let out = AsyncSignalHandler()\n var sources = [any DispatchSourceSignal]()\n for sig in on {\n signal(sig, SIG_IGN)\n let source = DispatchSource.makeSignalSource(signal: sig)\n source.setEventHandler {\n out.handler(sig)\n }\n source.resume()\n // Retain a reference to our signal sources so that they\n // do not go out of scope.\n sources.append(source)\n }\n out.state.withLock { $0.sources = sources }\n return out\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/IPAddress.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Facilitates conversion between IPv4 address representations.\npublic struct IPv4Address: Codable, CustomStringConvertible, Equatable, Sendable {\n /// The address as a 32-bit integer.\n public let value: UInt32\n\n /// Create an address from a dotted-decimal string, such as \"192.168.64.10\".\n public init(_ fromString: String) throws {\n let split = fromString.components(separatedBy: \".\")\n if split.count != 4 {\n throw NetworkAddressError.invalidStringAddress(address: fromString)\n }\n\n var parsedValue: UInt32 = 0\n for index in 0..<4 {\n guard let octet = UInt8(split[index]) else {\n throw NetworkAddressError.invalidStringAddress(address: fromString)\n }\n parsedValue |= UInt32(octet) << ((3 - index) * 8)\n }\n\n value = parsedValue\n }\n\n /// Create an address from an array of four bytes in network order (big-endian),\n /// such as [192, 168, 64, 10].\n public init(fromNetworkBytes: [UInt8]) throws {\n guard fromNetworkBytes.count == 4 else {\n throw NetworkAddressError.invalidNetworkByteAddress(address: fromNetworkBytes)\n }\n\n value =\n (UInt32(fromNetworkBytes[0]) << 24)\n | (UInt32(fromNetworkBytes[1]) << 16)\n | (UInt32(fromNetworkBytes[2]) << 8)\n | UInt32(fromNetworkBytes[3])\n }\n\n /// Create an address from a 32-bit integer, such as 0xc0a8_400a.\n public init(fromValue: UInt32) {\n value = fromValue\n }\n\n /// Retrieve the address as an array of bytes in network byte order.\n public var networkBytes: [UInt8] {\n [\n UInt8((value >> 24) & 0xff),\n UInt8((value >> 16) & 0xff),\n UInt8((value >> 8) & 0xff),\n UInt8(value & 0xff),\n ]\n }\n\n /// Retrieve the address as a dotted decimal string.\n public var description: String {\n networkBytes.map(String.init).joined(separator: \".\")\n }\n\n /// Create the base IPv4 address for a network that contains this\n /// address and uses the specified subnet mask length.\n public func prefix(prefixLength: PrefixLength) -> IPv4Address {\n IPv4Address(fromValue: value & prefixLength.prefixMask32)\n }\n}\n\nextension IPv4Address {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n let text = try container.decode(String.self)\n try self.init(text)\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n try container.encode(self.description)\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/ManagedProcess.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport GRPC\nimport Logging\nimport Synchronization\n\nfinal class ManagedProcess: Sendable {\n let id: String\n\n private let log: Logger\n private let process: Command\n private let lock: Mutex\n private let syncfd: Pipe\n private let owningPid: Int32?\n\n private struct State {\n init(io: IO) {\n self.io = io\n }\n\n let io: IO\n var waiters: [CheckedContinuation] = []\n var exitStatus: Int32? = nil\n var pid: Int32 = 0\n }\n\n var pid: Int32 {\n self.lock.withLock {\n $0.pid\n }\n }\n\n // swiftlint: disable type_name\n protocol IO {\n func start(process: inout Command) throws\n func closeAfterExec() throws\n func resize(size: Terminal.Size) throws\n func closeStdin() throws\n }\n // swiftlint: enable type_name\n\n static func localizeLogger(log: inout Logger, id: String) {\n log[metadataKey: \"id\"] = \"\\(id)\"\n }\n\n init(\n id: String,\n stdio: HostStdio,\n bundle: ContainerizationOCI.Bundle,\n owningPid: Int32? = nil,\n log: Logger\n ) throws {\n self.id = id\n var log = log\n Self.localizeLogger(log: &log, id: id)\n self.log = log\n self.owningPid = owningPid\n\n let syncfd = Pipe()\n try syncfd.setCloexec()\n self.syncfd = syncfd\n\n let args: [String]\n if let owningPid {\n args = [\n \"exec\",\n \"--parent-pid\",\n \"\\(owningPid)\",\n \"--process-path\",\n bundle.getExecSpecPath(id: id).path,\n ]\n } else {\n args = [\"run\", \"--bundle-path\", bundle.path.path]\n }\n\n var process = Command(\n \"/sbin/vmexec\",\n arguments: args,\n extraFiles: [syncfd.fileHandleForWriting]\n )\n\n var io: IO\n if stdio.terminal {\n log.info(\"setting up terminal IO\")\n let attrs = Command.Attrs(setsid: false, setctty: false)\n process.attrs = attrs\n io = try TerminalIO(\n stdio: stdio,\n log: log\n )\n } else {\n process.attrs = .init(setsid: false)\n io = StandardIO(\n stdio: stdio,\n log: log\n )\n }\n\n log.info(\"starting io\")\n\n // Setup IO early. We expect the host to be listening already.\n try io.start(process: &process)\n\n self.process = process\n self.lock = Mutex(State(io: io))\n }\n}\n\nextension ManagedProcess {\n func start() throws -> Int32 {\n try self.lock.withLock {\n log.info(\n \"starting managed process\",\n metadata: [\n \"id\": \"\\(id)\"\n ])\n\n // Start the underlying process.\n try process.start()\n\n // Close our side of any pipes.\n try syncfd.fileHandleForWriting.close()\n try $0.io.closeAfterExec()\n\n guard let piddata = try syncfd.fileHandleForReading.readToEnd() else {\n throw ContainerizationError(.internalError, message: \"no pid data from sync pipe\")\n }\n\n let i = piddata.withUnsafeBytes { ptr in\n ptr.load(as: Int32.self)\n }\n\n log.info(\"got back pid data \\(i)\")\n $0.pid = i\n\n log.info(\n \"started managed process\",\n metadata: [\n \"pid\": \"\\(i)\",\n \"id\": \"\\(id)\",\n ])\n\n return i\n }\n }\n\n func setExit(_ status: Int32) {\n self.lock.withLock {\n self.log.info(\n \"managed process exit\",\n metadata: [\n \"status\": \"\\(status)\"\n ])\n\n $0.exitStatus = status\n\n for waiter in $0.waiters {\n waiter.resume(returning: status)\n }\n\n self.log.debug(\"\\($0.waiters.count) managed process waiters signaled\")\n $0.waiters.removeAll()\n }\n }\n\n /// Wait on the process to exit\n func wait() async -> Int32 {\n await withCheckedContinuation { cont in\n self.lock.withLock {\n if let status = $0.exitStatus {\n cont.resume(returning: status)\n return\n }\n $0.waiters.append(cont)\n }\n }\n }\n\n func kill(_ signal: Int32) throws {\n try self.lock.withLock {\n guard $0.exitStatus == nil else {\n return\n }\n\n self.log.info(\"sending signal \\(signal) to process \\($0.pid)\")\n guard Foundation.kill($0.pid, signal) == 0 else {\n throw POSIXError.fromErrno()\n }\n }\n }\n\n func resize(size: Terminal.Size) throws {\n try self.lock.withLock {\n guard $0.exitStatus == nil else {\n return\n }\n try $0.io.resize(size: size)\n }\n }\n\n func closeStdin() throws {\n try self.lock.withLock {\n try $0.io.closeStdin()\n }\n }\n}\n"], ["/containerization/Sources/Containerization/VZVirtualMachine+Helpers.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport Logging\nimport Virtualization\nimport ContainerizationError\n\nextension VZVirtualMachine {\n nonisolated func connect(queue: DispatchQueue, port: UInt32) async throws -> VZVirtioSocketConnection {\n try await withCheckedThrowingContinuation { cont in\n queue.sync {\n guard let vsock = self.socketDevices[0] as? VZVirtioSocketDevice else {\n let error = ContainerizationError(.invalidArgument, message: \"no vsock device\")\n cont.resume(throwing: error)\n return\n }\n vsock.connect(toPort: port) { result in\n switch result {\n case .success(let conn):\n // `conn` isn't used concurrently.\n nonisolated(unsafe) let conn = conn\n cont.resume(returning: conn)\n case .failure(let error):\n cont.resume(throwing: error)\n }\n }\n }\n }\n }\n\n func listen(queue: DispatchQueue, port: UInt32, listener: VZVirtioSocketListener) throws {\n try queue.sync {\n guard let vsock = self.socketDevices[0] as? VZVirtioSocketDevice else {\n throw ContainerizationError(.invalidArgument, message: \"no vsock device\")\n }\n vsock.setSocketListener(listener, forPort: port)\n }\n }\n\n func removeListener(queue: DispatchQueue, port: UInt32) throws {\n try queue.sync {\n guard let vsock = self.socketDevices[0] as? VZVirtioSocketDevice else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"no vsock device to remove\"\n )\n }\n vsock.removeSocketListener(forPort: port)\n }\n }\n\n func start(queue: DispatchQueue) async throws {\n try await withCheckedThrowingContinuation { (cont: CheckedContinuation) in\n queue.sync {\n self.start { result in\n if case .failure(let error) = result {\n cont.resume(throwing: error)\n return\n }\n cont.resume()\n }\n }\n }\n }\n\n func stop(queue: DispatchQueue) async throws {\n try await withCheckedThrowingContinuation { (cont: CheckedContinuation) in\n queue.sync {\n self.stop { error in\n if let error {\n cont.resume(throwing: error)\n return\n }\n cont.resume()\n }\n }\n }\n }\n}\n\nextension VZVirtualMachine {\n func waitForAgent(queue: DispatchQueue) async throws -> FileHandle {\n let agentConnectionRetryCount: Int = 150\n let agentConnectionSleepDuration: Duration = .milliseconds(20)\n\n for _ in 0...agentConnectionRetryCount {\n do {\n return try await self.connect(queue: queue, port: Vminitd.port).dupHandle()\n } catch {\n try await Task.sleep(for: agentConnectionSleepDuration)\n continue\n }\n }\n throw ContainerizationError(.invalidArgument, message: \"no connection to agent socket\")\n }\n}\n\nextension VZVirtioSocketConnection {\n func dupHandle() -> FileHandle {\n let fd = dup(self.fileDescriptor)\n self.close()\n return FileHandle(fileDescriptor: fd, closeOnDealloc: false)\n }\n}\n\n#endif\n"], ["/containerization/Sources/Containerization/Image/ImageStore/ImageStore.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\n/// An ImageStore handles the mappings between an image's\n/// reference and the underlying descriptor inside of a content store.\npublic actor ImageStore: Sendable {\n /// The ImageStore path it was created with.\n public nonisolated let path: URL\n\n private let referenceManager: ReferenceManager\n internal let contentStore: ContentStore\n internal let lock: AsyncLock = AsyncLock()\n\n public init(path: URL, contentStore: ContentStore? = nil) throws {\n try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true)\n\n if let contentStore {\n self.contentStore = contentStore\n } else {\n self.contentStore = try LocalContentStore(path: path.appendingPathComponent(\"content\"))\n }\n\n self.path = path\n self.referenceManager = try ReferenceManager(path: path)\n }\n\n /// Return the default image store for the current user.\n public static let `default`: ImageStore = {\n do {\n let root = try defaultRoot()\n return try ImageStore(path: root)\n } catch {\n fatalError(\"unable to initialize default ImageStore \\(error)\")\n }\n }()\n\n private static func defaultRoot() throws -> URL {\n let root = FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first\n guard let root else {\n throw ContainerizationError(.notFound, message: \"unable to get Application Support directory for current user\")\n }\n return root.appendingPathComponent(\"com.apple.containerization\")\n\n }\n}\n\nextension ImageStore {\n /// Get an image from the `ImageStore`.\n ///\n /// - Parameters:\n /// - reference: Name of the image.\n /// - pull: Pull the image if it is not found.\n ///\n /// - Returns: A `Containerization.Image` object whose `reference` matches the given string.\n /// This method throws a `ContainerizationError(code: .notFound)` if the provided reference does not exist in the `ImageStore`.\n public func get(reference: String, pull: Bool = false) async throws -> Image {\n do {\n let desc = try await self.referenceManager.get(reference: reference)\n return Image(description: desc, contentStore: self.contentStore)\n } catch let error as ContainerizationError {\n if error.code == .notFound && pull {\n return try await self.pull(reference: reference)\n }\n throw error\n }\n }\n\n /// Get a list of all images in the `ImageStore`.\n ///\n /// - Returns: A `[Containerization.Image]` for all the images in the `ImageStore`.\n public func list() async throws -> [Image] {\n try await self.referenceManager.list().map { desc in\n Image(description: desc, contentStore: self.contentStore)\n }\n }\n\n /// Create a new image in the `ImageStore`.\n ///\n /// - Parameters:\n /// - description: The underlying `Image.Description` that contains information about the reference and index descriptor for the image to be created.\n ///\n /// - Note: It is assumed that the underlying manifests and blob layers for the image already exists in the `ContentStore` that the `ImageStore` was initialized with. This method is invoked when the `pull(...)` , `load(...)` and `tag(...)` methods are used.\n /// - Returns: A `Containerization.Image`\n @discardableResult\n internal func create(description: Image.Description) async throws -> Image {\n try await self.lock.withLock { ctx in\n try await self._create(description: description, lock: ctx)\n }\n }\n\n @discardableResult\n internal func _create(description: Image.Description, lock: AsyncLock.Context) async throws -> Image {\n try await self.referenceManager.create(description: description)\n return Image(description: description, contentStore: self.contentStore)\n }\n\n /// Delete an image from the `ImageStore`.\n ///\n /// - Parameters:\n /// - reference: Name of the image that is to be deleted.\n /// - performCleanup: Perform a garbage collection on the `ContentStore`, removing all unreferenced image layers and manifests,\n public func delete(reference: String, performCleanup: Bool = false) async throws {\n try await self.lock.withLock { lockCtx in\n try await self.referenceManager.delete(reference: reference)\n if performCleanup {\n try await self._prune(lockCtx)\n }\n }\n }\n\n /// Perform a garbage collection in the underlying `ContentStore` that is managed by the `ImageStore`.\n ///\n /// - Returns: Returns a tuple of `(deleted, freed)`.\n /// `deleted` : A list of the names of the content items that were deleted from the `ContentStore`,\n /// `freed` : The total size of the items that were deleted.\n @discardableResult\n public func prune() async throws -> (deleted: [String], freed: UInt64) {\n try await self.lock.withLock { lockCtx in\n try await self._prune(lockCtx)\n }\n }\n\n @discardableResult\n private func _prune(_ lock: AsyncLock.Context) async throws -> ([String], UInt64) {\n let images = try await self.list()\n var referenced: [String] = []\n for image in images {\n try await referenced.append(contentsOf: image.referencedDigests().uniqued())\n }\n let (deleted, size) = try await self.contentStore.delete(keeping: referenced)\n return (deleted, size)\n\n }\n\n /// Tag an existing image such that it can be referenced by another name.\n ///\n /// - Parameters:\n /// - existing: The reference to an image that already exists in the `ImageStore`.\n /// - new: The new reference by which the image should also be referenced as.\n /// - Note: The new image created in the `ImageStore` will have the same `Image.Description`\n /// as that of the image with reference `existing.`\n /// - Returns: A `Containerization.Image` object to the newly created image.\n public func tag(existing: String, new: String) async throws -> Image {\n let old = try await self.get(reference: existing)\n let descriptor = old.descriptor\n do {\n _ = try Reference.parse(new)\n } catch {\n throw ContainerizationError(.invalidArgument, message: \"Invalid reference \\(new). Error: \\(error)\")\n }\n let newDescription = Image.Description(reference: new, descriptor: descriptor)\n return try await self.create(description: newDescription)\n }\n}\n\nextension ImageStore {\n /// Pull an image and its associated manifest and blob layers from a remote registry.\n ///\n /// - Parameters:\n /// - reference: A string that references an image in a remote registry of the form `[:]/repository:`\n /// For example: \"docker.io/library/alpine:latest\".\n /// - platform: An optional parameter to indicate the platform to be pulled for the image.\n /// Defaults to `nil` signifying that layers for all supported platforms by the image will be pulled.\n /// - insecure: A boolean indicating if the connection to the remote registry should be made via plain-text http or not.\n /// Defaults to false, meaning the connection to the registry will be over https.\n /// - auth: An object that implements the `Authentication` protocol,\n /// used to add any credentials to the HTTP requests that are made to the registry.\n /// Defaults to `nil` meaning no additional credentials are added to any HTTP requests made to the registry.\n /// - progress: An optional handler over which progress update events about the pull operation can be received.\n ///\n /// - Returns: A `Containerization.Image` object to the newly pulled image.\n public func pull(\n reference: String, platform: Platform? = nil, insecure: Bool = false,\n auth: Authentication? = nil, progress: ProgressHandler? = nil\n ) async throws -> Image {\n\n let matcher = createPlatformMatcher(for: platform)\n let client = try RegistryClient(reference: reference, insecure: insecure, auth: auth)\n\n let ref = try Reference.parse(reference)\n let name = ref.path\n guard let tag = ref.tag ?? ref.digest else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid tag/digest for image reference \\(reference)\")\n }\n\n let rootDescriptor = try await client.resolve(name: name, tag: tag)\n let (id, tempDir) = try await self.contentStore.newIngestSession()\n let operation = ImportOperation(name: name, contentStore: self.contentStore, client: client, ingestDir: tempDir, progress: progress)\n do {\n let index = try await operation.import(root: rootDescriptor, matcher: matcher)\n return try await self.lock.withLock { lock in\n try await self.contentStore.completeIngestSession(id)\n let description = Image.Description(reference: reference, descriptor: index)\n let image = try await self._create(description: description, lock: lock)\n return image\n }\n } catch {\n try? await self.contentStore.cancelIngestSession(id)\n throw error\n }\n }\n\n /// Push an image and its associated manifest and blob layers to a remote registry.\n ///\n /// - Parameters:\n /// - reference: A string that references an image in the `ImageStore`. It must be of the form `[:]/repository:`\n /// For example: \"ghcr.io/foo-bar-baz/image:v1\".\n /// - platform: An optional parameter to indicate the platform to be pushed for the image.\n /// Defaults to `nil` signifying that layers for all supported platforms by the image will be pushed to the remote registry.\n /// - insecure: A boolean indicating if the connection to the remote registry should be made via plain-text http or not.\n /// Defaults to false, meaning the connection to the registry will be over https.\n /// - auth: An object that implements the `Authentication` protocol,\n /// used to add any credentials to the HTTP requests that are made to the registry.\n /// Defaults to `nil` meaning no additional credentials are added to any HTTP requests made to the registry.\n /// - progress: An optional handler over which progress update events about the push operation can be received.\n ///\n public func push(reference: String, platform: Platform? = nil, insecure: Bool = false, auth: Authentication? = nil, progress: ProgressHandler? = nil) async throws {\n let matcher = createPlatformMatcher(for: platform)\n let img = try await self.get(reference: reference)\n let allowedMediaTypes = [MediaTypes.dockerManifestList, MediaTypes.index]\n guard allowedMediaTypes.contains(img.mediaType) else {\n throw ContainerizationError(.internalError, message: \"Cannot push image \\(reference) with Index media type \\(img.mediaType)\")\n }\n let ref = try Reference.parse(reference)\n let name = ref.path\n guard let tag = ref.tag ?? ref.digest else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid tag/digest for image reference \\(reference)\")\n }\n let client = try RegistryClient(reference: reference, insecure: insecure, auth: auth)\n let operation = ExportOperation(name: name, tag: tag, contentStore: self.contentStore, client: client, progress: progress)\n try await operation.export(index: img.descriptor, platforms: matcher)\n }\n}\n\nextension ImageStore {\n /// Get the image for the init block from the image store.\n /// If the image does not exist locally, pull the image.\n public func getInitImage(reference: String, auth: Authentication? = nil, progress: ProgressHandler? = nil) async throws -> InitImage {\n do {\n let image = try await self.get(reference: reference)\n return InitImage(image: image)\n } catch let error as ContainerizationError {\n if error.code == .notFound {\n let image = try await self.pull(reference: reference, auth: auth, progress: progress)\n return InitImage(image: image)\n }\n throw error\n }\n }\n}\n"], ["/containerization/Sources/Containerization/HostsConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Static table lookups for a container. The values will be used to\n/// construct /etc/hosts for a given container.\npublic struct Hosts: Sendable {\n /// Represents one entry in an /etc/hosts file.\n public struct Entry: Sendable {\n /// The IPV4 or IPV6 address in String form.\n public var ipAddress: String\n /// The hostname(s) for the entry.\n public var hostnames: [String]\n /// An optional comment to be placed to the right side of the entry.\n public var comment: String?\n\n public init(ipAddress: String, hostnames: [String], comment: String? = nil) {\n self.comment = comment\n self.hostnames = hostnames\n self.ipAddress = ipAddress\n }\n\n /// The information in the structure rendered to a String representation\n /// that matches the format /etc/hosts expects.\n public var rendered: String {\n var line = ipAddress\n if !hostnames.isEmpty {\n line += \" \" + hostnames.joined(separator: \" \")\n }\n if let comment {\n line += \" # \\(comment) \"\n }\n return line\n }\n\n public static func localHostIPV4(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"127.0.0.1\",\n hostnames: [\"localhost\"],\n comment: comment\n )\n }\n\n public static func localHostIPV6(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"::1\",\n hostnames: [\"localhost\", \"ip6-localhost\", \"ip6-loopback\"],\n comment: comment\n )\n }\n\n public static func ipv6LocalNet(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"fe00::\",\n hostnames: [\"ip6-localnet\"],\n comment: comment\n )\n }\n\n public static func ipv6MulticastPrefix(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"ff00::\",\n hostnames: [\"ip6-mcastprefix\"],\n comment: comment\n )\n }\n\n public static func ipv6AllNodes(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"ff02::1\",\n hostnames: [\"ip6-allnodes\"],\n comment: comment\n )\n }\n\n public static func ipv6AllRouters(comment: String? = nil) -> Self {\n Self(\n ipAddress: \"ff02::2\",\n hostnames: [\"ip6-allrouters\"],\n comment: comment\n )\n }\n }\n\n /// The entries to be written to /etc/hosts.\n public var entries: [Entry]\n\n /// A comment to render at the top of the file.\n public var comment: String?\n\n public init(\n entries: [Entry],\n comment: String? = nil\n ) {\n self.entries = entries\n self.comment = comment\n }\n}\n\nextension Hosts {\n /// A default entry that can be used for convenience. It contains a IPV4\n /// and IPV6 localhost entry, as well as ipv6 localnet, ipv6 mcastprefix,\n /// ipv6 allnodes, and ipv6 allrouters.\n public static let `default` = Hosts(entries: [\n Entry.localHostIPV4(),\n Entry.localHostIPV6(),\n Entry.ipv6LocalNet(),\n Entry.ipv6MulticastPrefix(),\n Entry.ipv6AllNodes(),\n Entry.ipv6AllRouters(),\n ])\n\n /// Returns a string variant of the data that can be written to\n /// /etc/hosts directly.\n public var hostsFile: String {\n var lines: [String] = []\n\n if let comment {\n lines.append(\"# \\(comment)\")\n }\n\n for entry in entries {\n lines.append(entry.rendered)\n }\n\n return lines.joined(separator: \"\\n\") + \"\\n\"\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/WriteEntry.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CArchive\nimport Foundation\n\n/// Represents a single entry (e.g., a file, directory, symbolic link)\n/// that is to be read/written into an archive.\npublic final class WriteEntry {\n let underlying: OpaquePointer\n\n public init(_ archive: ArchiveWriter) {\n underlying = archive_entry_new2(archive.underlying)\n }\n\n public init() {\n underlying = archive_entry_new()\n }\n\n deinit {\n archive_entry_free(underlying)\n }\n}\n\nextension WriteEntry {\n /// The size of the entry in bytes.\n public var size: Int64? {\n get {\n guard archive_entry_size_is_set(underlying) != 0 else { return nil }\n return archive_entry_size(underlying)\n }\n set {\n if let s = newValue {\n archive_entry_set_size(underlying, s)\n } else {\n archive_entry_unset_size(underlying)\n }\n }\n }\n\n /// The mode of the entry.\n public var permissions: mode_t {\n get {\n archive_entry_perm(underlying)\n }\n set {\n archive_entry_set_perm(underlying, newValue)\n }\n }\n\n /// The owner id of the entry.\n public var owner: uid_t? {\n get {\n uid_t(exactly: archive_entry_uid(underlying))\n }\n set {\n archive_entry_set_uid(underlying, Int64(newValue ?? 0))\n }\n }\n\n /// The group id of the entry\n public var group: gid_t? {\n get {\n gid_t(exactly: archive_entry_gid(underlying))\n }\n set {\n archive_entry_set_gid(underlying, Int64(newValue ?? 0))\n }\n }\n\n /// The path of file this entry hardlinks to\n public var hardlink: String? {\n get {\n guard let cstr = archive_entry_hardlink(underlying) else {\n return nil\n }\n return String(cString: cstr)\n }\n set {\n guard let newValue else {\n archive_entry_set_hardlink(underlying, nil)\n return\n }\n newValue.withCString {\n archive_entry_set_hardlink(underlying, $0)\n }\n }\n }\n\n /// The UTF-8 encoded path of file this entry hardlinks to\n public var hardlinkUtf8: String? {\n get {\n guard let cstr = archive_entry_hardlink_utf8(underlying) else {\n return nil\n }\n return String(cString: cstr, encoding: .utf8)\n }\n set {\n guard let newValue else {\n archive_entry_set_hardlink_utf8(underlying, nil)\n return\n }\n newValue.withCString {\n archive_entry_set_hardlink_utf8(underlying, $0)\n }\n }\n }\n\n /// The string representation of the permissions of the entry\n public var strmode: String? {\n if let cstr = archive_entry_strmode(underlying) {\n return String(cString: cstr)\n }\n return nil\n }\n\n /// The type of file this entry represents.\n public var fileType: URLFileResourceType {\n get {\n switch archive_entry_filetype(underlying) {\n case S_IFIFO: return .namedPipe\n case S_IFCHR: return .characterSpecial\n case S_IFDIR: return .directory\n case S_IFBLK: return .blockSpecial\n case S_IFREG: return .regular\n case S_IFLNK: return .symbolicLink\n case S_IFSOCK: return .socket\n default: return .unknown\n }\n }\n set {\n switch newValue {\n case .namedPipe: archive_entry_set_filetype(underlying, UInt32(S_IFIFO as mode_t))\n case .characterSpecial: archive_entry_set_filetype(underlying, UInt32(S_IFCHR as mode_t))\n case .directory: archive_entry_set_filetype(underlying, UInt32(S_IFDIR as mode_t))\n case .blockSpecial: archive_entry_set_filetype(underlying, UInt32(S_IFBLK as mode_t))\n case .regular: archive_entry_set_filetype(underlying, UInt32(S_IFREG as mode_t))\n case .symbolicLink: archive_entry_set_filetype(underlying, UInt32(S_IFLNK as mode_t))\n case .socket: archive_entry_set_filetype(underlying, UInt32(S_IFSOCK as mode_t))\n default: archive_entry_set_filetype(underlying, 0)\n }\n }\n }\n\n /// The date that the entry was last accessed\n public var contentAccessDate: Date? {\n get {\n Date(\n underlying,\n archive_entry_atime_is_set,\n archive_entry_atime,\n archive_entry_atime_nsec)\n }\n set {\n setDate(\n newValue,\n underlying, archive_entry_set_atime,\n archive_entry_unset_atime)\n }\n }\n\n /// The date that the entry was created\n public var creationDate: Date? {\n get {\n Date(\n underlying,\n archive_entry_ctime_is_set,\n archive_entry_ctime,\n archive_entry_ctime_nsec)\n }\n set {\n setDate(\n newValue,\n underlying, archive_entry_set_ctime,\n archive_entry_unset_ctime)\n }\n }\n\n /// The date that the entry was modified\n public var modificationDate: Date? {\n get {\n Date(\n underlying,\n archive_entry_mtime_is_set,\n archive_entry_mtime,\n archive_entry_mtime_nsec)\n }\n set {\n setDate(\n newValue,\n underlying, archive_entry_set_mtime,\n archive_entry_unset_mtime)\n }\n }\n\n /// The file path of the entry\n public var path: String? {\n get {\n guard let pathname = archive_entry_pathname(underlying) else {\n return nil\n }\n return String(cString: pathname)\n }\n set {\n guard let newValue else {\n archive_entry_set_pathname(underlying, nil)\n return\n }\n newValue.withCString {\n archive_entry_set_pathname(underlying, $0)\n }\n }\n }\n\n /// The UTF-8 encoded file path of the entry\n public var pathUtf8: String? {\n get {\n guard let pathname = archive_entry_pathname_utf8(underlying) else {\n return nil\n }\n return String(cString: pathname)\n }\n set {\n guard let newValue else {\n archive_entry_set_pathname_utf8(underlying, nil)\n return\n }\n newValue.withCString {\n archive_entry_set_pathname_utf8(underlying, $0)\n }\n }\n }\n\n /// The symlink target that the entry points to\n public var symlinkTarget: String? {\n get {\n guard let target = archive_entry_symlink(underlying) else {\n return nil\n }\n return String(cString: target)\n }\n set {\n guard let newValue else {\n archive_entry_set_symlink(underlying, nil)\n return\n }\n newValue.withCString {\n archive_entry_set_symlink(underlying, $0)\n }\n }\n }\n\n /// The extended attributes of the entry\n public var xattrs: [String: Data] {\n get {\n archive_entry_xattr_reset(self.underlying)\n var attrs: [String: Data] = [:]\n var namePtr: UnsafePointer?\n var valuePtr: UnsafeRawPointer?\n var size: Int = 0\n while archive_entry_xattr_next(self.underlying, &namePtr, &valuePtr, &size) == 0 {\n let _name = namePtr.map { String(cString: $0) }\n let _value = valuePtr.map { Data(bytes: $0, count: size) }\n guard let name = _name, let value = _value else {\n continue\n }\n attrs[name] = value\n }\n return attrs\n }\n set {\n archive_entry_xattr_clear(self.underlying)\n for (key, value) in newValue {\n value.withUnsafeBytes { ptr in\n archive_entry_xattr_add_entry(self.underlying, key, ptr.baseAddress, [UInt8](value).count)\n }\n }\n }\n }\n\n fileprivate func setDate(\n _ date: Date?, _ underlying: OpaquePointer, _ setter: (OpaquePointer, time_t, CLong) -> Void,\n _ unset: (OpaquePointer) -> Void\n ) {\n if let d = date {\n let ti = d.timeIntervalSince1970\n let seconds = floor(ti)\n let nsec = max(0, min(1_000_000_000, ti - seconds * 1_000_000_000))\n setter(underlying, time_t(seconds), CLong(nsec))\n } else {\n unset(underlying)\n }\n }\n}\n\nextension Date {\n init?(\n _ underlying: OpaquePointer, _ isSet: (OpaquePointer) -> CInt, _ seconds: (OpaquePointer) -> time_t,\n _ nsec: (OpaquePointer) -> CLong\n ) {\n guard isSet(underlying) != 0 else { return nil }\n let ti = TimeInterval(seconds(underlying)) + TimeInterval(nsec(underlying)) * 0.000_000_001\n self.init(timeIntervalSince1970: ti)\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/NetworkAddress+Allocator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension IPv4Address {\n /// Creates an allocator for IPv4 addresses.\n public static func allocator(lower: UInt32, size: Int) throws -> any AddressAllocator {\n // NOTE: 2^31 - 1 size limit in the very improbable case that we run on 32-bit.\n guard size > 0 && size < Int.max && 0xffff_ffff - lower >= size - 1 else {\n throw AllocatorError.rangeExceeded\n }\n return IndexedAddressAllocator(\n size: size,\n addressToIndex: { address in\n guard address.value >= lower && address.value - lower <= UInt32(size) else {\n return nil\n }\n return Int(address.value - lower)\n },\n indexToAddress: { IPv4Address(fromValue: lower + UInt32($0)) }\n )\n }\n}\n\nextension UInt16 {\n /// Creates an allocator for TCP/UDP ports and other UInt16 values.\n public static func allocator(lower: UInt16, size: Int) throws -> any AddressAllocator {\n guard 0xffff - lower + 1 >= size else {\n throw AllocatorError.rangeExceeded\n }\n\n return IndexedAddressAllocator(\n size: size,\n addressToIndex: { address in\n guard address >= lower && address <= lower + UInt16(size) else {\n return nil\n }\n return Int(address - lower)\n },\n indexToAddress: { lower + UInt16($0) }\n )\n }\n}\n\nextension UInt32 {\n /// Creates an allocator for vsock ports, or any UInt32 values.\n public static func allocator(lower: UInt32, size: Int) throws -> any AddressAllocator {\n guard 0xffff_ffff - lower + 1 >= size else {\n throw AllocatorError.rangeExceeded\n }\n\n return IndexedAddressAllocator(\n size: size,\n addressToIndex: { address in\n guard address >= lower && address <= lower + UInt32(size) else {\n return nil\n }\n return Int(address - lower)\n },\n indexToAddress: { lower + UInt32($0) }\n )\n }\n\n /// Creates a rotating allocator for vsock ports, or any UInt32 values.\n public static func rotatingAllocator(lower: UInt32, size: UInt32) throws -> any AddressAllocator {\n guard 0xffff_ffff - lower + 1 >= size else {\n throw AllocatorError.rangeExceeded\n }\n\n return RotatingAddressAllocator(\n size: size,\n addressToIndex: { address in\n guard address >= lower && address <= lower + UInt32(size) else {\n return nil\n }\n return Int(address - lower)\n },\n indexToAddress: { lower + UInt32($0) }\n )\n }\n}\n\nextension Character {\n private static let deviceLetters = Array(\"abcdefghijklmnopqrstuvwxyz\")\n\n /// Creates an allocator for block device tags, or any character values.\n public static func blockDeviceTagAllocator() -> any AddressAllocator {\n IndexedAddressAllocator(\n size: Self.deviceLetters.count,\n addressToIndex: { address in\n Self.deviceLetters.firstIndex(of: address)\n },\n indexToAddress: { Self.deviceLetters[$0] }\n )\n }\n}\n"], ["/containerization/Sources/Containerization/Image/ImageStore/ImageStore+ReferenceManager.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\nextension ImageStore {\n /// A ReferenceManager handles the mappings between an image's\n /// reference and the underlying descriptor inside of a content store.\n internal actor ReferenceManager: Sendable {\n private let path: URL\n\n private typealias State = [String: Descriptor]\n private var images: State\n\n public init(path: URL) throws {\n try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true)\n\n self.path = path\n self.images = [:]\n }\n\n private func load() throws -> State {\n let statePath = self.path.appendingPathComponent(\"state.json\")\n guard FileManager.default.fileExists(atPath: statePath.absolutePath()) else {\n return [:]\n }\n do {\n let data = try Data(contentsOf: statePath)\n return try JSONDecoder().decode(State.self, from: data)\n } catch {\n throw ContainerizationError(.internalError, message: \"Failed to load image state \\(error.localizedDescription)\")\n }\n }\n\n private func save(_ state: State) throws {\n let statePath = self.path.appendingPathComponent(\"state.json\")\n try JSONEncoder().encode(state).write(to: statePath)\n }\n\n public func delete(reference: String) throws {\n var state = try self.load()\n state.removeValue(forKey: reference)\n try self.save(state)\n }\n\n public func delete(image: Image.Description) throws {\n try self.delete(reference: image.reference)\n }\n\n public func create(description: Image.Description) throws {\n var state = try self.load()\n state[description.reference] = description.descriptor\n try self.save(state)\n }\n\n public func list() throws -> [Image.Description] {\n let state = try self.load()\n return state.map { key, val in\n let description = Image.Description(reference: key, descriptor: val)\n return description\n }\n }\n\n public func get(reference: String) throws -> Image.Description {\n let images = try self.list()\n let hit = images.first(where: { image in\n image.reference == reference\n })\n guard let hit else {\n throw ContainerizationError(.notFound, message: \"image \\(reference) not found\")\n }\n return hit\n }\n }\n}\n"], ["/containerization/Sources/Containerization/VZVirtualMachineManager.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport Logging\n\n/// A virtualization.framework backed `VirtualMachineManager` implementation.\npublic struct VZVirtualMachineManager: VirtualMachineManager {\n private let kernel: Kernel\n private let bootlog: String?\n private let initialFilesystem: Mount\n private let logger: Logger?\n\n public init(\n kernel: Kernel,\n initialFilesystem: Mount,\n bootlog: String? = nil,\n logger: Logger? = nil\n ) {\n self.kernel = kernel\n self.bootlog = bootlog\n self.initialFilesystem = initialFilesystem\n self.logger = logger\n }\n\n public func create(container: Container) throws -> any VirtualMachineInstance {\n guard let c = container as? LinuxContainer else {\n throw ContainerizationError(\n .invalidArgument,\n message: \"provided container is not a LinuxContainer\"\n )\n }\n\n return try VZVirtualMachineInstance(\n logger: self.logger,\n with: { config in\n config.cpus = container.cpus\n config.memoryInBytes = container.memoryInBytes\n\n config.kernel = self.kernel\n config.initialFilesystem = self.initialFilesystem\n\n config.interfaces = container.interfaces\n if let bootlog {\n config.bootlog = URL(filePath: bootlog)\n }\n config.rosetta = c.config.rosetta\n config.nestedVirtualization = c.config.virtualization\n\n config.mounts = [c.rootfs] + c.config.mounts\n })\n }\n}\n#endif\n"], ["/containerization/Sources/ContainerizationOS/Command.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CShim\nimport Foundation\nimport Synchronization\n\n#if canImport(Darwin)\nimport Darwin\nprivate let _kill = Darwin.kill\n#elseif canImport(Musl)\nimport Musl\nprivate let _kill = Musl.kill\n#elseif canImport(Glibc)\nimport Glibc\nprivate let _kill = Glibc.kill\n#endif\n\n/// Use a command to run an executable.\npublic struct Command: Sendable {\n /// Path to the executable binary.\n public var executable: String\n /// Arguments provided to the binary.\n public var arguments: [String]\n /// Environment variables for the process.\n public var environment: [String]\n /// The directory where the process should execute.\n public var directory: String?\n /// Additional files to pass to the process.\n public var extraFiles: [FileHandle]\n /// The standard input.\n public var stdin: FileHandle?\n /// The standard output.\n public var stdout: FileHandle?\n /// The standard error.\n public var stderr: FileHandle?\n\n private let state: State\n\n /// System level attributes to set on the process.\n public struct Attrs: Sendable {\n /// Set pgroup for the new process.\n public var setPGroup: Bool\n /// Inherit the real uid/gid of the parent.\n public var resetIDs: Bool\n /// Reset the child's signal handlers to the default.\n public var setSignalDefault: Bool\n /// The initial signal mask for the process.\n public var signalMask: UInt32\n /// Create a new session for the process.\n public var setsid: Bool\n /// Set the controlling terminal for the process to fd 0.\n public var setctty: Bool\n /// Set the process user ID.\n public var uid: UInt32?\n /// Set the process group ID.\n public var gid: UInt32?\n\n public init(\n setPGroup: Bool = false,\n resetIDs: Bool = false,\n setSignalDefault: Bool = true,\n signalMask: UInt32 = 0,\n setsid: Bool = false,\n setctty: Bool = false,\n uid: UInt32? = nil,\n gid: UInt32? = nil\n ) {\n self.setPGroup = setPGroup\n self.resetIDs = resetIDs\n self.setSignalDefault = setSignalDefault\n self.signalMask = signalMask\n self.setsid = setsid\n self.setctty = setctty\n self.uid = uid\n self.gid = gid\n }\n }\n\n private final class State: Sendable {\n let pid: Atomic = Atomic(-1)\n }\n\n /// Attributes to set on the process.\n public var attrs = Attrs()\n\n /// System level process identifier.\n public var pid: Int32 { self.state.pid.load(ordering: .acquiring) }\n\n public init(\n _ executable: String,\n arguments: [String] = [],\n environment: [String] = environment(),\n directory: String? = nil,\n extraFiles: [FileHandle] = []\n ) {\n self.executable = executable\n self.arguments = arguments\n self.environment = environment\n self.extraFiles = extraFiles\n self.directory = directory\n self.state = State()\n }\n\n public static func environment() -> [String] {\n ProcessInfo.processInfo.environment\n .map { \"\\($0)=\\($1)\" }\n }\n}\n\nextension Command {\n public enum Error: Swift.Error, CustomStringConvertible {\n case processRunning\n\n public var description: String {\n switch self {\n case .processRunning:\n return \"the process is already running\"\n }\n }\n }\n}\n\nextension Command {\n @discardableResult\n public func kill(_ signal: Int32) -> Int32? {\n let pid = self.pid\n guard pid > 0 else {\n return nil\n }\n return _kill(pid, signal)\n }\n}\n\nextension Command {\n /// Start the process.\n public func start() throws {\n guard self.pid == -1 else {\n throw Error.processRunning\n }\n let child = try execute()\n self.state.pid.store(child, ordering: .releasing)\n }\n\n /// Wait for the process to exit and return the exit status.\n @discardableResult\n public func wait() throws -> Int32 {\n var rus = rusage()\n var ws = Int32()\n\n let pid = self.pid\n guard pid > 0 else {\n return -1\n }\n\n let result = wait4(pid, &ws, 0, &rus)\n guard result == pid else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n return Self.toExitStatus(ws)\n }\n\n private func execute() throws -> pid_t {\n var attrs = exec_command_attrs()\n exec_command_attrs_init(&attrs)\n\n let set = try createFileset()\n defer {\n try? set.null.close()\n }\n var fds = [Int32](repeating: 0, count: set.handles.count)\n for (i, handle) in set.handles.enumerated() {\n fds[i] = handle.fileDescriptor\n }\n\n attrs.setsid = self.attrs.setsid ? 1 : 0\n attrs.setctty = self.attrs.setctty ? 1 : 0\n attrs.setpgid = self.attrs.setPGroup ? 1 : 0\n\n var cwdPath: UnsafeMutablePointer?\n if let chdir = self.directory {\n cwdPath = strdup(chdir)\n }\n defer {\n if let cwdPath {\n free(cwdPath)\n }\n }\n\n if let uid = self.attrs.uid {\n attrs.uid = uid\n }\n if let gid = self.attrs.gid {\n attrs.gid = gid\n }\n\n var pid: pid_t = 0\n var argv = ([executable] + arguments).map { strdup($0) } + [nil]\n defer {\n for arg in argv where arg != nil {\n free(arg)\n }\n }\n\n let env = environment.map { strdup($0) } + [nil]\n defer {\n for e in env where e != nil {\n free(e)\n }\n }\n\n let result = fds.withUnsafeBufferPointer { file_handles in\n exec_command(\n &pid,\n argv[0],\n &argv,\n env,\n file_handles.baseAddress!, Int32(file_handles.count),\n cwdPath ?? nil,\n &attrs)\n }\n guard result == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n\n return pid\n }\n\n /// Create a posix_spawn file actions set of fds to pass to the new process\n private func createFileset() throws -> (null: FileHandle, handles: [FileHandle]) {\n // grab dev null incase a handle passed by the user is nil\n let null = try openDevNull()\n var files = [FileHandle]()\n files.append(stdin ?? null)\n files.append(stdout ?? null)\n files.append(stderr ?? null)\n files.append(contentsOf: extraFiles)\n return (null: null, handles: files)\n }\n\n /// Returns a file handle to /dev/null.\n private func openDevNull() throws -> FileHandle {\n let fd = open(\"/dev/null\", O_WRONLY, 0)\n guard fd > 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n return FileHandle(fileDescriptor: fd, closeOnDealloc: false)\n }\n}\n\nextension Command {\n private static let signalOffset: Int32 = 128\n\n private static let shift: Int32 = 8\n private static let mask: Int32 = 0x7F\n private static let stopped: Int32 = 0x7F\n private static let exited: Int32 = 0x00\n\n static func signaled(_ ws: Int32) -> Bool {\n ws & mask != stopped && ws & mask != exited\n }\n\n static func exited(_ ws: Int32) -> Bool {\n ws & mask == exited\n }\n\n static func exitStatus(_ ws: Int32) -> Int32 {\n let r: Int32\n #if os(Linux)\n r = ws >> shift & 0xFF\n #else\n r = ws >> shift\n #endif\n return r\n }\n\n public static func toExitStatus(_ ws: Int32) -> Int32 {\n if signaled(ws) {\n // We use the offset as that is how existing container\n // runtimes minic bash for the status when signaled.\n return Int32(Self.signalOffset + ws & mask)\n }\n if exited(ws) {\n return exitStatus(ws)\n }\n return ws\n }\n\n}\n\nprivate func WIFEXITED(_ status: Int32) -> Bool {\n _WSTATUS(status) == 0\n}\n\nprivate func _WSTATUS(_ status: Int32) -> Int32 {\n status & 0x7f\n}\n\nprivate func WIFSIGNALED(_ status: Int32) -> Bool {\n (_WSTATUS(status) != 0) && (_WSTATUS(status) != 0x7f)\n}\n\nprivate func WEXITSTATUS(_ status: Int32) -> Int32 {\n (status >> 8) & 0xff\n}\n\nprivate func WTERMSIG(_ status: Int32) -> Int32 {\n status & 0x7f\n}\n"], ["/containerization/Sources/ContainerizationExtras/CIDRAddress.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Describes an IPv4 CIDR address block.\npublic struct CIDRAddress: CustomStringConvertible, Equatable, Sendable {\n\n /// The base IPv4 address of the CIDR block.\n public let lower: IPv4Address\n\n /// The last IPv4 address of the CIDR block\n public let upper: IPv4Address\n\n /// The IPv4 address component of the CIDR block.\n public let address: IPv4Address\n\n /// The address prefix length for the CIDR block, which determines its size.\n public let prefixLength: PrefixLength\n\n /// Create an CIDR address block from its text representation.\n public init(_ cidr: String) throws {\n let split = cidr.components(separatedBy: \"/\")\n guard split.count == 2 else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n address = try IPv4Address(split[0])\n guard let prefixLength = PrefixLength(split[1]) else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n guard prefixLength >= 0 && prefixLength <= 32 else {\n throw NetworkAddressError.invalidCIDR(cidr: cidr)\n }\n\n self.prefixLength = prefixLength\n lower = address.prefix(prefixLength: prefixLength)\n upper = IPv4Address(fromValue: lower.value + prefixLength.suffixMask32)\n }\n\n /// Create a CIDR address from a member IP and a prefix length.\n public init(_ address: IPv4Address, prefixLength: PrefixLength) throws {\n guard prefixLength >= 0 && prefixLength <= 32 else {\n throw NetworkAddressError.invalidCIDR(cidr: \"\\(address)/\\(prefixLength)\")\n }\n\n self.prefixLength = prefixLength\n self.address = address\n lower = address.prefix(prefixLength: prefixLength)\n upper = IPv4Address(fromValue: lower.value + prefixLength.suffixMask32)\n }\n\n /// Create the smallest CIDR block that includes the lower and upper bounds.\n public init(lower: IPv4Address, upper: IPv4Address) throws {\n guard lower.value <= upper.value else {\n throw NetworkAddressError.invalidAddressRange(lower: lower.description, upper: upper.description)\n }\n\n address = lower\n for prefixLength: PrefixLength in 1...32 {\n // find the first case where a subnet mask would put lower and upper in different CIDR block\n let mask = prefixLength.prefixMask32\n\n if (lower.value & mask) != (upper.value & mask) {\n self.prefixLength = prefixLength - 1\n self.lower = address.prefix(prefixLength: self.prefixLength)\n self.upper = IPv4Address(fromValue: self.lower.value + self.prefixLength.suffixMask32)\n return\n }\n }\n\n // if lower and upper are same, create a /32 block\n self.prefixLength = 32\n self.lower = lower\n self.upper = upper\n }\n\n /// Get the offset of the specified address, relative to the\n /// base address for the CIDR block, returning nil if the block\n /// does not contain the address.\n public func getIndex(_ address: IPv4Address) -> UInt32? {\n guard address.value >= lower.value && address.value <= upper.value else {\n return nil\n }\n\n return address.value - lower.value\n }\n\n /// Return true if the CIDR block contains the specified address.\n public func contains(ipv4: IPv4Address) -> Bool {\n lower.value <= ipv4.value && ipv4.value <= upper.value\n }\n\n /// Return true if the CIDR block contains all addresses of another CIDR block.\n public func contains(cidr: CIDRAddress) -> Bool {\n lower.value <= cidr.lower.value && cidr.upper.value <= upper.value\n }\n\n /// Return true if the CIDR block shares any addresses with another CIDR block.\n public func overlaps(cidr: CIDRAddress) -> Bool {\n (lower.value <= cidr.lower.value && upper.value >= cidr.lower.value)\n || (upper.value >= cidr.upper.value && lower.value <= cidr.upper.value)\n }\n\n /// Retrieve the text representation of the CIDR block.\n public var description: String {\n \"\\(address)/\\(prefixLength)\"\n }\n}\n\nextension CIDRAddress: Codable {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n let text = try container.decode(String.self)\n try self.init(text)\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n try container.encode(self.description)\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/VsockProxy.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationIO\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport SendableProperty\n\nfinal class VsockProxy: Sendable {\n enum Action {\n case listen\n case dial\n }\n\n private enum SocketType {\n case unix\n case vsock\n }\n\n init(\n id: String,\n action: Action,\n port: UInt32,\n path: URL,\n udsPerms: UInt32?,\n log: Logger? = nil\n ) {\n self.id = id\n self.action = action\n self.port = port\n self.path = path\n self.udsPerms = udsPerms\n self.log = log\n }\n\n public let id: String\n private let path: URL\n private let action: Action\n private let port: UInt32\n private let udsPerms: UInt32?\n private let log: Logger?\n\n @SendableProperty\n private var listener: Socket?\n private let task = Mutex?>(nil)\n}\n\nextension VsockProxy {\n func close() throws {\n guard let listener else {\n return\n }\n\n try listener.close()\n let fm = FileManager.default\n if fm.fileExists(atPath: self.path.path) {\n try FileManager.default.removeItem(at: self.path)\n }\n let task = task.withLock { $0 }\n task?.cancel()\n }\n\n func start() throws {\n switch self.action {\n case .dial:\n try dialHost()\n case .listen:\n try dialGuest()\n }\n }\n\n private func dialHost() throws {\n let fm = FileManager.default\n\n let parentDir = self.path.deletingLastPathComponent()\n try fm.createDirectory(\n at: parentDir,\n withIntermediateDirectories: true\n )\n\n let type = try UnixType(\n path: self.path.path,\n perms: self.udsPerms,\n unlinkExisting: true\n )\n let uds = try Socket(type: type)\n try uds.listen()\n listener = uds\n\n try self.acceptLoop(socketType: .unix)\n }\n\n private func dialGuest() throws {\n let type = VsockType(\n port: self.port,\n cid: VsockType.anyCID\n )\n let vsock = try Socket(type: type)\n try vsock.listen()\n listener = vsock\n\n try self.acceptLoop(socketType: .vsock)\n }\n\n private func acceptLoop(socketType: SocketType) throws {\n guard let listener else {\n return\n }\n\n let stream = try listener.acceptStream()\n let task = Task {\n do {\n for try await conn in stream {\n Task {\n do {\n try await handleConn(\n conn: conn,\n connType: socketType\n )\n } catch {\n self.log?.error(\"failed to handle connection: \\(error)\")\n }\n }\n }\n } catch {\n self.log?.error(\"failed to accept connection: \\(error)\")\n }\n }\n self.task.withLock { $0 = task }\n }\n\n private func handleConn(\n conn: ContainerizationOS.Socket,\n connType: SocketType\n ) async throws {\n try await withCheckedThrowingContinuation { (c: CheckedContinuation) in\n do {\n // `relayTo` isn't used concurrently.\n nonisolated(unsafe) var relayTo: ContainerizationOS.Socket\n\n switch connType {\n case .unix:\n let type = VsockType(\n port: self.port,\n cid: VsockType.hostCID\n )\n relayTo = try Socket(\n type: type,\n closeOnDeinit: false\n )\n case .vsock:\n let type = try UnixType(path: self.path.path)\n relayTo = try Socket(\n type: type,\n closeOnDeinit: false\n )\n }\n\n try relayTo.connect()\n\n // `clientFile` isn't used concurrently.\n nonisolated(unsafe) var clientFile = OSFile.SpliceFile(fd: conn.fileDescriptor)\n // `serverFile` isn't used concurrently.\n nonisolated(unsafe) var serverFile = OSFile.SpliceFile(fd: relayTo.fileDescriptor)\n\n let cleanup = { @Sendable in\n do {\n try ProcessSupervisor.default.poller.delete(clientFile.fileDescriptor)\n try ProcessSupervisor.default.poller.delete(serverFile.fileDescriptor)\n try conn.close()\n try relayTo.close()\n } catch {\n self.log?.error(\"Failed to clean up vsock proxy: \\(error)\")\n }\n c.resume()\n }\n\n try! ProcessSupervisor.default.poller.add(clientFile.fileDescriptor, mask: EPOLLIN | EPOLLOUT) { mask in\n if mask.readyToRead {\n do {\n let (_, _, action) = try OSFile.splice(from: &clientFile, to: &serverFile)\n if action == .eof || action == .brokenPipe {\n return cleanup()\n }\n } catch {\n return cleanup()\n }\n }\n\n if mask.readyToWrite {\n do {\n let (_, _, action) = try OSFile.splice(from: &serverFile, to: &clientFile)\n if action == .eof || action == .brokenPipe {\n return cleanup()\n }\n } catch {\n return cleanup()\n }\n }\n\n if mask.isHangup {\n return cleanup()\n }\n }\n\n try! ProcessSupervisor.default.poller.add(serverFile.fileDescriptor, mask: EPOLLIN | EPOLLOUT) { mask in\n if mask.readyToRead {\n do {\n let (_, _, action) = try OSFile.splice(from: &serverFile, to: &clientFile)\n if action == .eof || action == .brokenPipe {\n return cleanup()\n }\n } catch {\n return cleanup()\n }\n }\n\n if mask.readyToWrite {\n do {\n let (_, _, action) = try OSFile.splice(from: &clientFile, to: &serverFile)\n if action == .eof || action == .brokenPipe {\n return cleanup()\n }\n } catch {\n return cleanup()\n }\n }\n\n if mask.isHangup {\n return cleanup()\n }\n }\n } catch {\n c.resume(throwing: error)\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/RegistryClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport NIO\nimport NIOHTTP1\n\n#if os(macOS)\nimport Network\n#endif\n\n/// Data used to control retry behavior for `RegistryClient`.\npublic struct RetryOptions: Sendable {\n /// The maximum number of retries to attempt before failing.\n public var maxRetries: Int\n /// The retry interval in nanoseconds.\n public var retryInterval: UInt64\n /// A provided closure to handle if a given HTTP response should be\n /// retried.\n public var shouldRetry: (@Sendable (HTTPClientResponse) -> Bool)?\n\n public init(maxRetries: Int, retryInterval: UInt64, shouldRetry: (@Sendable (HTTPClientResponse) -> Bool)? = nil) {\n self.maxRetries = maxRetries\n self.retryInterval = retryInterval\n self.shouldRetry = shouldRetry\n }\n}\n\n/// A client for interacting with OCI compliant container registries.\npublic final class RegistryClient: ContentClient {\n private static let defaultRetryOptions = RetryOptions(\n maxRetries: 3,\n retryInterval: 1_000_000_000,\n shouldRetry: ({ response in\n response.status.code >= 500\n })\n )\n\n let client: HTTPClient\n let base: URLComponents\n let clientID: String\n let authentication: Authentication?\n let retryOptions: RetryOptions?\n let bufferSize: Int\n\n public convenience init(\n reference: String,\n insecure: Bool = false,\n auth: Authentication? = nil,\n logger: Logger? = nil\n ) throws {\n let ref = try Reference.parse(reference)\n guard let domain = ref.resolvedDomain else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid domain for image reference \\(reference)\")\n }\n let scheme = insecure ? \"http\" : \"https\"\n let _url = \"\\(scheme)://\\(domain)\"\n guard let url = URL(string: _url) else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot convert \\(_url) to URL\")\n }\n guard let host = url.host else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid host \\(domain)\")\n }\n let port = url.port\n self.init(\n host: host,\n scheme: scheme,\n port: port,\n authentication: auth,\n retryOptions: Self.defaultRetryOptions\n )\n }\n\n public init(\n host: String,\n scheme: String? = \"https\",\n port: Int? = nil,\n authentication: Authentication? = nil,\n clientID: String? = nil,\n retryOptions: RetryOptions? = nil,\n bufferSize: Int = Int(4.mib()),\n logger: Logger? = nil\n ) {\n var components = URLComponents()\n components.scheme = scheme\n components.host = host\n components.port = port\n\n self.base = components\n self.clientID = clientID ?? \"containerization-registry-client\"\n self.authentication = authentication\n self.retryOptions = retryOptions\n self.bufferSize = bufferSize\n var httpConfiguration = HTTPClient.Configuration()\n let proxyConfig: HTTPClient.Configuration.Proxy? = {\n let proxyEnv = ProcessInfo.processInfo.environment[\"HTTP_PROXY\"]\n guard let proxyEnv else {\n return nil\n }\n guard let url = URL(string: proxyEnv), let host = url.host(), let port = url.port else {\n return nil\n }\n return .server(host: host, port: port)\n }()\n httpConfiguration.proxy = proxyConfig\n if let logger {\n self.client = HTTPClient(eventLoopGroupProvider: .singleton, configuration: httpConfiguration, backgroundActivityLogger: logger)\n } else {\n self.client = HTTPClient(eventLoopGroupProvider: .singleton, configuration: httpConfiguration)\n }\n }\n\n deinit {\n _ = client.shutdown()\n }\n\n func host() -> String {\n base.host ?? \"\"\n }\n\n internal func request(\n components: URLComponents,\n method: HTTPMethod = .GET,\n bodyClosure: () throws -> HTTPClientRequest.Body? = { nil },\n headers: [(String, String)]? = nil,\n closure: (HTTPClientResponse) async throws -> T\n ) async throws -> T {\n guard let path = components.url?.absoluteString else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid url \\(components.path)\")\n }\n\n var request = HTTPClientRequest(url: path)\n request.method = method\n\n var currentToken: TokenResponse?\n let token: String? = try await {\n if let basicAuth = authentication {\n return try await basicAuth.token()\n }\n return nil\n }()\n\n if let token {\n request.headers.add(name: \"Authorization\", value: \"\\(token)\")\n }\n\n // Add any arbitrary headers\n headers?.forEach { (k, v) in request.headers.add(name: k, value: v) }\n var retryCount = 0\n var response: HTTPClientResponse?\n while true {\n request.body = try bodyClosure()\n do {\n let _response = try await client.execute(request, deadline: .distantFuture)\n response = _response\n if _response.status == .unauthorized || _response.status == .forbidden {\n let authHeader = _response.headers[TokenRequest.authenticateHeaderName]\n let tokenRequest: TokenRequest\n do {\n tokenRequest = try self.createTokenRequest(parsing: authHeader)\n } catch {\n // The server did not tell us how to authenticate our requests,\n // Or we do not support scheme the server is requesting for.\n // Throw the 401/403 to the caller, and let them decide how to proceed.\n throw RegistryClient.Error.invalidStatus(url: path, _response.status, reason: String(describing: error))\n }\n if let ct = currentToken, ct.isValid(scope: tokenRequest.scope) {\n break\n }\n\n do {\n let _currentToken = try await fetchToken(request: tokenRequest)\n guard let token = _currentToken.getToken() else {\n throw ContainerizationError(.internalError, message: \"Failed to fetch Bearer token\")\n }\n currentToken = _currentToken\n request.headers.replaceOrAdd(name: \"Authorization\", value: token)\n retryCount += 1\n } catch let err as RegistryClient.Error {\n guard case .invalidStatus(_, let status, _) = err else {\n throw err\n }\n if status == .unauthorized || status == .forbidden {\n throw RegistryClient.Error.invalidStatus(url: path, _response.status, reason: \"Access denied or wrong credentials\")\n }\n\n throw err\n }\n\n continue\n }\n guard let retryOptions = self.retryOptions else {\n break\n }\n guard retryCount < retryOptions.maxRetries else {\n break\n }\n guard let shouldRetry = retryOptions.shouldRetry, shouldRetry(_response) else {\n break\n }\n retryCount += 1\n try await Task.sleep(nanoseconds: retryOptions.retryInterval)\n continue\n } catch let err as RegistryClient.Error {\n throw err\n } catch {\n #if os(macOS)\n if let err = error as? NWError {\n if err.errorCode == kDNSServiceErr_NoSuchRecord {\n throw ContainerizationError(.internalError, message: \"No Such DNS Record \\(host())\")\n }\n }\n #endif\n guard let retryOptions = self.retryOptions, retryCount < retryOptions.maxRetries else {\n throw error\n }\n retryCount += 1\n try await Task.sleep(nanoseconds: retryOptions.retryInterval)\n }\n }\n guard let response else {\n throw ContainerizationError(.internalError, message: \"Invalid response\")\n }\n return try await closure(response)\n }\n\n internal func requestData(\n components: URLComponents,\n headers: [(String, String)]? = nil\n ) async throws -> Data {\n let bytes: ByteBuffer = try await requestBuffer(components: components, headers: headers)\n return Data(buffer: bytes)\n }\n\n internal func requestBuffer(\n components: URLComponents,\n headers: [(String, String)]? = nil\n ) async throws -> ByteBuffer {\n try await request(components: components, method: .GET, headers: headers) { response in\n guard response.status == .ok else {\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n\n return try await response.body.collect(upTo: self.bufferSize)\n }\n }\n\n internal func requestJSON(\n components: URLComponents,\n headers: [(String, String)]? = nil\n ) async throws -> T {\n let buffer = try await self.requestBuffer(components: components, headers: headers)\n return try JSONDecoder().decode(T.self, from: buffer)\n }\n\n /// A minimal endpoint, mounted at /v2/ will provide version support information based on its response statuses.\n /// See https://distribution.github.io/distribution/spec/api/#api-version-check\n public func ping() async throws {\n var components = base\n components.path = \"/v2/\"\n\n try await request(components: components) { response in\n guard response.status == .ok else {\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n }\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/Server.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\nimport GRPC\nimport Logging\nimport Musl\nimport NIOCore\nimport NIOPosix\n\nfinal class Initd: Sendable {\n let log: Logger\n let state: State\n let group: MultiThreadedEventLoopGroup\n\n actor State {\n var containers: [String: ManagedContainer] = [:]\n var proxies: [String: VsockProxy] = [:]\n\n func get(container id: String) throws -> ManagedContainer {\n guard let ctr = self.containers[id] else {\n throw ContainerizationError(\n .notFound,\n message: \"container \\(id) not found\"\n )\n }\n return ctr\n }\n\n func add(container: ManagedContainer) throws {\n guard containers[container.id] == nil else {\n throw ContainerizationError(\n .exists,\n message: \"container \\(container.id) already exists\"\n )\n }\n containers[container.id] = container\n }\n\n func add(proxy: VsockProxy) throws {\n guard proxies[proxy.id] == nil else {\n throw ContainerizationError(\n .exists,\n message: \"proxy \\(proxy.id) already exists\"\n )\n }\n proxies[proxy.id] = proxy\n }\n\n func remove(proxy id: String) throws -> VsockProxy {\n guard let proxy = proxies.removeValue(forKey: id) else {\n throw ContainerizationError(\n .notFound,\n message: \"proxy \\(id) does not exist\"\n )\n }\n return proxy\n }\n\n func remove(container id: String) throws {\n guard let _ = containers.removeValue(forKey: id) else {\n throw ContainerizationError(\n .notFound,\n message: \"container \\(id) does not exist\"\n )\n }\n }\n }\n\n init(log: Logger, group: MultiThreadedEventLoopGroup) {\n self.log = log\n self.group = group\n self.state = State()\n }\n\n func serve(port: Int) async throws {\n try await withThrowingTaskGroup(of: Void.self) { group in\n log.debug(\"starting process supervisor\")\n\n await ProcessSupervisor.default.setLog(self.log)\n await ProcessSupervisor.default.ready()\n\n log.debug(\n \"booting grpc server on vsock\",\n metadata: [\n \"port\": \"\\(port)\"\n ])\n let server = try await Server.start(\n configuration: .default(\n target: .vsockAddress(.init(cid: .any, port: .init(port))),\n eventLoopGroup: self.group,\n serviceProviders: [self])\n ).get()\n log.info(\n \"grpc api serving on vsock\",\n metadata: [\n \"port\": \"\\(port)\"\n ])\n\n group.addTask {\n try await server.onClose.get()\n }\n try await group.next()\n group.cancelAll()\n }\n }\n}\n"], ["/containerization/Sources/Containerization/VsockConnectionStream.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n#if os(macOS)\nimport Virtualization\n#endif\n\n/// A stream of vsock connections.\npublic final class VsockConnectionStream: NSObject, Sendable {\n /// A stream of connections dialed from the remote.\n public let connections: AsyncStream\n /// The port the connections are for.\n public let port: UInt32\n\n private let cont: AsyncStream.Continuation\n\n public init(port: UInt32) {\n self.port = port\n let (stream, continuation) = AsyncStream.makeStream(of: FileHandle.self)\n self.connections = stream\n self.cont = continuation\n }\n\n public func finish() {\n self.cont.finish()\n }\n}\n\n#if os(macOS)\n\nextension VsockConnectionStream: VZVirtioSocketListenerDelegate {\n public func listener(\n _: VZVirtioSocketListener, shouldAcceptNewConnection conn: VZVirtioSocketConnection,\n from _: VZVirtioSocketDevice\n ) -> Bool {\n let fd = dup(conn.fileDescriptor)\n conn.close()\n\n cont.yield(FileHandle(fileDescriptor: fd, closeOnDealloc: false))\n return true\n }\n}\n\n#endif\n"], ["/containerization/Sources/ContainerizationOS/Linux/Epoll.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(Linux)\n\n#if canImport(Musl)\nimport Musl\n#elseif canImport(Glibc)\nimport Glibc\n#else\n#error(\"Epoll not supported on this platform\")\n#endif\n\nimport Foundation\nimport Synchronization\n\n/// Register file descriptors to receive events via Linux's\n/// epoll syscall surface.\npublic final class Epoll: Sendable {\n public typealias Mask = Int32\n public typealias Handler = (@Sendable (Mask) -> Void)\n\n private let epollFD: Int32\n private let handlers = SafeMap()\n private let pipe = Pipe() // to wake up a waiting epoll_wait\n\n public init() throws {\n let efd = epoll_create1(EPOLL_CLOEXEC)\n guard efd > 0 else {\n throw POSIXError.fromErrno()\n }\n self.epollFD = efd\n try self.add(pipe.fileHandleForReading.fileDescriptor) { _ in }\n }\n\n public func add(\n _ fd: Int32,\n mask: Int32 = EPOLLIN | EPOLLOUT, // HUP is always added\n handler: @escaping Handler\n ) throws {\n guard fcntl(fd, F_SETFL, O_NONBLOCK) == 0 else {\n throw POSIXError.fromErrno()\n }\n\n let events = EPOLLET | UInt32(bitPattern: mask)\n\n var event = epoll_event()\n event.events = events\n event.data.fd = fd\n\n try withUnsafeMutablePointer(to: &event) { ptr in\n while true {\n if epoll_ctl(self.epollFD, EPOLL_CTL_ADD, fd, ptr) == -1 {\n if errno == EAGAIN || errno == EINTR {\n continue\n }\n throw POSIXError.fromErrno()\n }\n break\n }\n }\n\n self.handlers.set(fd, handler)\n }\n\n /// Run the main epoll loop.\n ///\n /// max events to return in a single wait\n /// timeout in ms.\n /// -1 means block forever.\n /// 0 means return immediately if no events.\n public func run(maxEvents: Int = 128, timeout: Int32 = -1) throws {\n var events: [epoll_event] = .init(\n repeating: epoll_event(),\n count: maxEvents\n )\n\n while true {\n let n = epoll_wait(self.epollFD, &events, Int32(events.count), timeout)\n guard n >= 0 else {\n if errno == EINTR || errno == EAGAIN {\n continue // go back to epoll_wait\n }\n throw POSIXError.fromErrno()\n }\n\n if n == 0 {\n return // if epoll wait times out, then n will be 0\n }\n\n for i in 0.. Bool {\n errno == ENOENT || errno == EBADF || errno == EPERM\n }\n\n /// Shutdown the epoll handler.\n public func shutdown() throws {\n // wakes up epoll_wait and triggers a shutdown\n try self.pipe.fileHandleForWriting.close()\n }\n\n private final class SafeMap: Sendable {\n let dict = Mutex<[Key: Value]>([:])\n\n func set(_ key: Key, _ value: Value) {\n dict.withLock { @Sendable in\n $0[key] = value\n }\n }\n\n func get(_ key: Key) -> Value? {\n dict.withLock { @Sendable in\n $0[key]\n }\n }\n\n func del(_ key: Key) {\n dict.withLock { @Sendable in\n _ = $0.removeValue(forKey: key)\n }\n }\n }\n}\n\nextension Epoll.Mask {\n public var isHangup: Bool {\n (self & (EPOLLHUP | EPOLLERR | EPOLLRDHUP)) != 0\n }\n\n public var readyToRead: Bool {\n (self & EPOLLIN) != 0\n }\n\n public var readyToWrite: Bool {\n (self & EPOLLOUT) != 0\n }\n}\n\n#endif // os(Linux)\n"], ["/containerization/Sources/SendableProperty/Synchronized.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// `Synchronization` will be automatically imported with `SendableProperty`.\n@_exported import Synchronization\n\n/// A synchronization primitive that protects shared mutable state via mutual exclusion.\npublic final class Synchronized: Sendable {\n private let lock: Mutex\n\n private struct State: @unchecked Sendable {\n var value: T\n }\n\n /// Creates a new instance.\n /// - Parameter value: The initial value.\n public init(_ value: T) {\n self.lock = Mutex(State(value: value))\n }\n\n /// Calls the given closure after acquiring the lock and returns its value.\n /// - Parameter body: The body of code to execute while the lock is held.\n public func withLock(_ body: (inout T) throws -> R) rethrows -> R {\n try lock.withLock { state in\n try body(&state.value)\n }\n }\n}\n"], ["/containerization/Sources/Containerization/Image/Image.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\n\n/// Type representing an OCI container image.\npublic struct Image: Sendable {\n private let contentStore: ContentStore\n /// The description for the image that comprises of its name and a reference to its root descriptor.\n public let description: Description\n\n /// A description of the OCI image.\n public struct Description: Sendable {\n /// The string reference of the image.\n public let reference: String\n /// The descriptor identifying the image.\n public let descriptor: Descriptor\n /// The digest for the image.\n public var digest: String { descriptor.digest }\n /// The media type of the image.\n public var mediaType: String { descriptor.mediaType }\n\n public init(reference: String, descriptor: Descriptor) {\n self.reference = reference\n self.descriptor = descriptor\n }\n }\n\n /// The descriptor for the image.\n public var descriptor: Descriptor { description.descriptor }\n /// The digest of the image.\n public var digest: String { description.digest }\n /// The media type of the image.\n public var mediaType: String { description.mediaType }\n /// The string reference for the image.\n public var reference: String { description.reference }\n\n public init(description: Description, contentStore: ContentStore) {\n self.description = description\n self.contentStore = contentStore\n }\n\n /// Returns the underlying OCI index for the image.\n public func index() async throws -> Index {\n guard let content: Content = try await contentStore.get(digest: digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(digest)\")\n }\n return try content.decode()\n }\n\n /// Returns the manifest for the specified platform.\n public func manifest(for platform: Platform) async throws -> Manifest {\n let index = try await self.index()\n let desc = index.manifests.first { desc in\n desc.platform == platform\n }\n guard let desc else {\n throw ContainerizationError(.unsupported, message: \"Platform \\(platform.description)\")\n }\n guard let content: Content = try await contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(digest)\")\n }\n return try content.decode()\n }\n\n /// Returns the descriptor for the given platform. If it does not exist\n /// will throw a ContainerizationError with the code set to .invalidArgument.\n public func descriptor(for platform: Platform) async throws -> Descriptor {\n let index = try await self.index()\n let desc = index.manifests.first { $0.platform == platform }\n guard let desc else {\n throw ContainerizationError(.invalidArgument, message: \"unsupported platform \\(platform)\")\n }\n return desc\n }\n\n /// Returns the OCI config for the specified platform.\n public func config(for platform: Platform) async throws -> ContainerizationOCI.Image {\n let manifest = try await self.manifest(for: platform)\n let desc = manifest.config\n guard let content: Content = try await contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(digest)\")\n }\n return try content.decode()\n }\n\n /// Returns a list of digests to all the referenced OCI objects.\n public func referencedDigests() async throws -> [String] {\n var referenced: [String] = [self.digest.trimmingDigestPrefix]\n let index = try await self.index()\n for manifest in index.manifests {\n referenced.append(manifest.digest.trimmingDigestPrefix)\n guard let m: Manifest = try? await contentStore.get(digest: manifest.digest) else {\n // If the requested digest does not exist or is not a manifest. Skip.\n // Its safe to skip processing this digest as it wont have any child layers.\n continue\n }\n let descs = m.layers + [m.config]\n referenced.append(contentsOf: descs.map { $0.digest.trimmingDigestPrefix })\n }\n return referenced\n }\n\n /// Returns a reference to the content blob for the image. The specified digest must be referenced by the image in one of its layers.\n public func getContent(digest: String) async throws -> Content {\n guard try await self.referencedDigests().contains(digest.trimmingDigestPrefix) else {\n throw ContainerizationError(.internalError, message: \"Image \\(self.reference) does not reference digest \\(digest)\")\n }\n guard let content: Content = try await contentStore.get(digest: digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(digest)\")\n }\n return content\n }\n}\n"], ["/containerization/Sources/cctl/ImageCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\nextension Application {\n struct Images: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"images\",\n abstract: \"Manage images\",\n subcommands: [\n Get.self,\n Delete.self,\n Pull.self,\n Tag.self,\n Push.self,\n Save.self,\n Load.self,\n ]\n )\n\n func run() async throws {\n let store = Application.imageStore\n let images = try await store.list()\n\n print(\"REFERENCE\\tMEDIA TYPE\\tDIGEST\")\n for image in images {\n print(\"\\(image.reference)\\t\\(image.mediaType)\\t\\(image.digest)\")\n }\n }\n\n struct Delete: AsyncParsableCommand {\n @Argument var reference: String\n\n func run() async throws {\n let store = Application.imageStore\n try await store.delete(reference: reference)\n }\n }\n\n struct Tag: AsyncParsableCommand {\n @Argument var old: String\n @Argument var new: String\n\n func run() async throws {\n let store = Application.imageStore\n _ = try await store.tag(existing: old, new: new)\n }\n }\n\n struct Get: AsyncParsableCommand {\n @Argument var reference: String\n\n func run() async throws {\n let store = Application.imageStore\n let image = try await store.get(reference: reference)\n\n let index = try await image.index()\n\n let enc = JSONEncoder()\n enc.outputFormatting = .prettyPrinted\n let data = try enc.encode(ImageDisplay(reference: image.reference, index: index))\n print(String(data: data, encoding: .utf8)!)\n }\n }\n\n struct ImageDisplay: Codable {\n let reference: String\n let index: Index\n }\n\n struct Pull: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"pull\",\n abstract: \"Pull an image's contents into a content store\"\n )\n\n @Argument var ref: String\n\n @Option(name: .customLong(\"platform\"), help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platformString: String?\n\n @Option(\n name: .customLong(\"unpack-path\"), help: \"Path to a new directory to unpack the image into\",\n transform: { str in\n URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)\n })\n var unpackPath: String?\n\n @Flag(help: \"Pull via plain text http\") var http: Bool = false\n\n func run() async throws {\n let imageStore = Application.imageStore\n let platform: Platform? = try {\n if let platformString {\n return try Platform(from: platformString)\n }\n return nil\n }()\n\n let reference = try Reference.parse(ref)\n reference.normalize()\n let normalizedReference = reference.description\n if normalizedReference != ref {\n print(\"Reference resolved to \\(reference.description)\")\n }\n\n let image = try await Images.withAuthentication(ref: normalizedReference) { auth in\n try await imageStore.pull(reference: normalizedReference, platform: platform, insecure: http, auth: auth)\n }\n\n guard let image else {\n print(\"image pull failed\")\n Application.exit(withError: POSIXError(.EACCES))\n }\n\n print(\"image pulled\")\n guard let unpackPath else {\n return\n }\n guard !FileManager.default.fileExists(atPath: unpackPath) else {\n throw ContainerizationError(.exists, message: \"Directory already exists at \\(unpackPath)\")\n }\n let unpackUrl = URL(filePath: unpackPath)\n try FileManager.default.createDirectory(at: unpackUrl, withIntermediateDirectories: true)\n\n let unpacker = EXT4Unpacker.init(blockSizeInBytes: 2.gib())\n\n if let platform {\n let name = platform.description.replacingOccurrences(of: \"/\", with: \"-\")\n let _ = try await unpacker.unpack(image, for: platform, at: unpackUrl.appending(component: name))\n } else {\n for descriptor in try await image.index().manifests {\n if let referenceType = descriptor.annotations?[\"vnd.docker.reference.type\"], referenceType == \"attestation-manifest\" {\n continue\n }\n guard let descPlatform = descriptor.platform else {\n continue\n }\n let name = descPlatform.description.replacingOccurrences(of: \"/\", with: \"-\")\n let _ = try await unpacker.unpack(image, for: descPlatform, at: unpackUrl.appending(component: name))\n print(\"created snapshot for platform \\(descPlatform.description)\")\n }\n }\n }\n }\n\n struct Push: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"push\",\n abstract: \"Push an image to a remote registry\"\n )\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platformString: String?\n\n @Flag(help: \"Push via plain text http\") var http: Bool = false\n\n @Argument var ref: String\n\n func run() async throws {\n let imageStore = Application.imageStore\n let platform: Platform? = try {\n if let platformString {\n return try Platform(from: platformString)\n }\n return nil\n }()\n\n let reference = try Reference.parse(ref)\n reference.normalize()\n let normalizedReference = reference.description\n if normalizedReference != ref {\n print(\"Reference resolved to \\(reference.description)\")\n }\n\n try await Images.withAuthentication(ref: normalizedReference) { auth in\n try await imageStore.push(reference: normalizedReference, platform: platform, insecure: http, auth: auth)\n }\n print(\"image pushed\")\n }\n }\n\n struct Save: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"save\",\n abstract: \"Save one or more images to a tar archive\"\n )\n\n @Option(help: \"Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'\") var platform: String?\n\n @Option(name: .shortAndLong, help: \"Path to tar archive\")\n var output: String\n\n @Argument var reference: [String]\n\n func run() async throws {\n var p: Platform? = nil\n if let platform {\n p = try Platform(from: platform)\n }\n let store = Application.imageStore\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n try await store.save(references: reference, out: tempDir, platform: p)\n let writer = try ArchiveWriter(format: .pax, filter: .none, file: URL(filePath: output))\n try writer.archiveDirectory(tempDir)\n try writer.finishEncoding()\n print(\"image exported\")\n }\n }\n\n struct Load: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"load\",\n abstract: \"Load one or more images from a tar archive\"\n )\n\n @Option(name: .shortAndLong, help: \"Path to tar archive\")\n var input: String\n\n func run() async throws {\n let store = Application.imageStore\n let tarFile = URL(fileURLWithPath: input)\n let reader = try ArchiveReader(file: tarFile.absoluteURL)\n let tempDir = FileManager.default.uniqueTemporaryDirectory()\n defer {\n try? FileManager.default.removeItem(at: tempDir)\n }\n try reader.extractContents(to: tempDir)\n let imported = try await store.load(from: tempDir)\n for image in imported {\n print(\"imported \\(image.reference)\")\n }\n }\n }\n\n private static func withAuthentication(\n ref: String, _ body: @Sendable @escaping (_ auth: Authentication?) async throws -> T?\n ) async throws -> T? {\n var authentication: Authentication?\n let ref = try Reference.parse(ref)\n guard let host = ref.resolvedDomain else {\n throw ContainerizationError(.invalidArgument, message: \"No host specified in image reference\")\n }\n authentication = Self.authenticationFromEnv(host: host)\n if let authentication {\n return try await body(authentication)\n }\n let keychain = KeychainHelper(id: Application.keychainID)\n authentication = try? keychain.lookup(domain: host)\n return try await body(authentication)\n }\n\n private static func authenticationFromEnv(host: String) -> Authentication? {\n let env = ProcessInfo.processInfo.environment\n guard env[\"REGISTRY_HOST\"] == host else {\n return nil\n }\n guard let user = env[\"REGISTRY_USERNAME\"], let password = env[\"REGISTRY_TOKEN\"] else {\n return nil\n }\n return BasicAuthentication(username: user, password: password)\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/LocalContentStore.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// swiftlint:disable unused_optional_binding\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport Crypto\nimport Foundation\n\n/// A `ContentStore` implementation that stores content on the local filesystem.\npublic actor LocalContentStore: ContentStore {\n private static let encoder = JSONEncoder()\n\n private let _basePath: URL\n private let _ingestPath: URL\n private let _blobPath: URL\n private let _lock: AsyncLock\n\n private var activeIngestSessions: AsyncSet = AsyncSet([])\n\n /// Create a new `LocalContentStore`.\n ///\n /// - Parameters:\n /// - path: The path where content should be written under.\n public init(path: URL) throws {\n let ingestPath = path.appendingPathComponent(\"ingest\")\n let blobPath = path.appendingPathComponent(\"blobs/sha256\")\n\n let fileManager = FileManager.default\n try fileManager.createDirectory(at: ingestPath, withIntermediateDirectories: true)\n try fileManager.createDirectory(at: blobPath, withIntermediateDirectories: true)\n\n self._basePath = path\n self._ingestPath = ingestPath\n self._blobPath = blobPath\n self._lock = AsyncLock()\n Self.encoder.outputFormatting = .sortedKeys\n }\n\n /// Get a piece of content from the store. Returns nil if not\n /// found.\n ///\n /// - Parameters:\n /// - digest: The string digest of the content.\n public func get(digest: String) throws -> Content? {\n let d = digest.trimmingDigestPrefix\n let path = self._blobPath.appendingPathComponent(d)\n do {\n return try LocalContent(path: path)\n } catch let err as ContainerizationError {\n switch err.code {\n case .notFound:\n return nil\n default:\n throw err\n }\n }\n }\n\n /// Get a piece of content from the store and return the decoded version of\n /// it.\n ///\n /// - Parameters:\n /// - digest: The string digest of the content.\n public func get(digest: String) throws -> T? {\n guard let content: Content = try self.get(digest: digest) else {\n return nil\n }\n return try content.decode()\n }\n\n /// Delete all content besides a set provided.\n ///\n /// - Parameters:\n /// - keeping: The set of string digests to keep.\n public func delete(keeping: [String]) async throws -> ([String], UInt64) {\n let fileManager = FileManager.default\n let all = try fileManager.contentsOfDirectory(at: self._blobPath, includingPropertiesForKeys: nil)\n let allDigests = Set(all.map { $0.lastPathComponent })\n let toDelete = allDigests.subtracting(keeping)\n return try await self.delete(digests: Array(toDelete))\n }\n\n /// Delete a specific set of content.\n ///\n /// - Parameters:\n /// - digests: Array of strings denoting the digests of the content to delete.\n @discardableResult\n public func delete(digests: [String]) async throws -> ([String], UInt64) {\n let store = AsyncStore<([String], UInt64)>()\n try await self._lock.withLock { context in\n let fileManager = FileManager.default\n var deleted: [String] = []\n var deletedBytes: UInt64 = 0\n for toDelete in digests {\n let p = self._blobPath.appendingPathComponent(toDelete)\n guard let content = try? LocalContent(path: p) else {\n continue\n }\n deletedBytes += try content.size()\n try fileManager.removeItem(at: p)\n deleted.append(toDelete)\n }\n await store.set((deleted, deletedBytes))\n }\n return await store.get() ?? ([], 0)\n }\n\n /// Creates a transactional write to the content store.\n ///\n /// - Parameters:\n /// - body: Closure that is given a temporary `URL` of the base directory which all contents should be written to.\n /// This is a transaction write where any failed operation in the closure (caught exception) will result in all contents written\n /// in the closure to be deleted. If the closure succeeds, then all the content that have been written to the temporary `URL`\n /// will be moved into the actual blobs path of the content store.\n @discardableResult\n public func ingest(_ body: @Sendable @escaping (URL) async throws -> Void) async throws -> [String] {\n let (id, tempPath) = try await self.newIngestSession()\n try await body(tempPath)\n return try await self.completeIngestSession(id)\n }\n\n /// Creates a new ingest session and returns the session ID and temporary ingest directory corresponding to the session.\n /// The contents from the ingest directory are processed and moved into the content store once the session is marked complete.\n /// This can be done by invoking the `completeIngestSession` method with the returned session ID.\n public func newIngestSession() async throws -> (id: String, ingestDir: URL) {\n let id = UUID().uuidString\n let temporaryPath = self._ingestPath.appendingPathComponent(id)\n let fileManager = FileManager.default\n try fileManager.createDirectory(atPath: temporaryPath.path, withIntermediateDirectories: true)\n await self.activeIngestSessions.insert(id)\n return (id, temporaryPath)\n }\n\n /// Completes a previously started ingest session corresponding to `id`. The contents from the ingest\n /// directory from the session are moved into the content store atomically. Any failure encountered will\n /// result in a transaction failure causing none of the contents to be ingested into the store.\n /// - Parameters:\n /// - id: id of the ingest session to complete.\n @discardableResult\n public func completeIngestSession(_ id: String) async throws -> [String] {\n guard await activeIngestSessions.contains(id) else {\n throw ContainerizationError(.internalError, message: \"Invalid session id \\(id)\")\n }\n await activeIngestSessions.remove(id)\n let temporaryPath = self._ingestPath.appendingPathComponent(id)\n let fileManager = FileManager.default\n defer {\n try? fileManager.removeItem(at: temporaryPath)\n }\n let tempDigests: [URL] = try fileManager.contentsOfDirectory(at: temporaryPath, includingPropertiesForKeys: nil)\n return try await self._lock.withLock { context in\n var moved: [String] = []\n let fileManager = FileManager.default\n do {\n try tempDigests.forEach {\n let digest = $0.lastPathComponent\n let target = self._blobPath.appendingPathComponent(digest)\n // only ingest if not exists\n if !fileManager.fileExists(atPath: target.path) {\n try fileManager.moveItem(at: $0, to: target)\n moved.append(digest)\n }\n }\n } catch {\n moved.forEach {\n try? fileManager.removeItem(at: self._blobPath.appendingPathComponent($0))\n }\n throw error\n }\n return tempDigests.map { $0.lastPathComponent }\n }\n }\n\n /// Cancels a previously started ingest session corresponding to `id`.\n /// The contents from the ingest directory corresponding to the session are removed.\n /// - Parameters:\n /// - id: id of the ingest session to complete.\n public func cancelIngestSession(_ id: String) async throws {\n guard let _ = await self.activeIngestSessions.remove(id) else {\n return\n }\n let temporaryPath = self._ingestPath.appendingPathComponent(id)\n let fileManager = FileManager.default\n try? fileManager.removeItem(at: temporaryPath)\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4Reader+Export.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationArchive\nimport Foundation\nimport SystemPackage\n\nextension EXT4.EXT4Reader {\n public func export(archive: FilePath) throws {\n let config = ArchiveWriterConfiguration(\n format: .paxRestricted, filter: .none, options: [Options.xattrformat(.schily)])\n let writer = try ArchiveWriter(configuration: config)\n try writer.open(file: archive.url)\n var items = self.tree.root.pointee.children\n let hardlinkedInodes = Set(self.hardlinks.values)\n var hardlinkTargets: [EXT4.InodeNumber: FilePath] = [:]\n\n while items.count > 0 {\n let itemPtr = items.removeFirst()\n let item = itemPtr.pointee\n let inode = try self.getInode(number: item.inode)\n let entry = WriteEntry()\n let mode = inode.mode\n let size: UInt64 = (UInt64(inode.sizeHigh) << 32) | UInt64(inode.sizeLow)\n entry.permissions = mode\n guard let path = item.path else {\n continue\n }\n if hardlinkedInodes.contains(item.inode) {\n hardlinkTargets[item.inode] = path\n }\n guard self.hardlinks[path] == nil else {\n continue\n }\n var attributes: [EXT4.ExtendedAttribute] = []\n let buffer: [UInt8] = EXT4.tupleToArray(inode.inlineXattrs)\n if !buffer.allZeros {\n try attributes.append(contentsOf: Self.readInlineExtendedAttributes(from: buffer))\n }\n if inode.xattrBlockLow != 0 {\n let block = inode.xattrBlockLow\n try self.seek(block: block)\n guard let buffer = try self.handle.read(upToCount: Int(self.blockSize)) else {\n throw EXT4.Error.couldNotReadBlock(block)\n }\n try attributes.append(contentsOf: Self.readBlockExtendedAttributes(from: [UInt8](buffer)))\n }\n\n var xattrs: [String: Data] = [:]\n for attribute in attributes {\n guard attribute.fullName != \"system.data\" else {\n continue\n }\n xattrs[attribute.fullName] = Data(attribute.value)\n }\n\n let pathStr = path.description\n entry.path = pathStr\n entry.size = Int64(size)\n entry.group = gid_t(inode.gid)\n entry.owner = uid_t(inode.uid)\n entry.creationDate = Date(fsTimestamp: UInt64((inode.ctimeExtra << 32) | inode.ctime))\n entry.modificationDate = Date(fsTimestamp: UInt64((inode.mtimeExtra << 32) | inode.mtime))\n entry.contentAccessDate = Date(fsTimestamp: UInt64((inode.atimeExtra << 32) | inode.atime))\n entry.xattrs = xattrs\n\n if mode.isDir() {\n entry.fileType = .directory\n for child in item.children {\n items.append(child)\n }\n if pathStr == \"\" {\n continue\n }\n try writer.writeEntry(entry: entry, data: nil)\n } else if mode.isReg() {\n entry.fileType = .regular\n var data = Data()\n var remaining: UInt64 = size\n if let block = item.blocks {\n for dataBlock in block.start.. self.blockSize {\n count = self.blockSize\n } else {\n count = remaining\n }\n guard let dataBytes = try self.handle.read(upToCount: Int(count)) else {\n throw EXT4.Error.couldNotReadBlock(dataBlock)\n }\n data.append(dataBytes)\n remaining -= UInt64(dataBytes.count)\n }\n }\n if let additionalBlocks = item.additionalBlocks {\n for block in additionalBlocks {\n for dataBlock in block.start.. self.blockSize {\n count = self.blockSize\n } else {\n count = remaining\n }\n guard let dataBytes = try self.handle.read(upToCount: Int(count)) else {\n throw EXT4.Error.couldNotReadBlock(dataBlock)\n }\n data.append(dataBytes)\n remaining -= UInt64(dataBytes.count)\n }\n }\n }\n try writer.writeEntry(entry: entry, data: data)\n } else if mode.isLink() {\n entry.fileType = .symbolicLink\n if size < 60 {\n let linkBytes = EXT4.tupleToArray(inode.block)\n entry.symlinkTarget = String(bytes: linkBytes, encoding: .utf8) ?? \"\"\n } else {\n if let block = item.blocks {\n try self.seek(block: block.start)\n guard let linkBytes = try self.handle.read(upToCount: Int(size)) else {\n throw EXT4.Error.couldNotReadBlock(block.start)\n }\n entry.symlinkTarget = String(bytes: linkBytes, encoding: .utf8) ?? \"\"\n }\n }\n try writer.writeEntry(entry: entry, data: nil)\n } else { // do not process sockets, fifo, character and block devices\n continue\n }\n }\n for (path, number) in self.hardlinks {\n guard let targetPath = hardlinkTargets[number] else {\n continue\n }\n let inode = try self.getInode(number: number)\n let entry = WriteEntry()\n entry.path = path.description\n entry.hardlink = targetPath.description\n entry.permissions = inode.mode\n entry.group = gid_t(inode.gid)\n entry.owner = uid_t(inode.uid)\n entry.creationDate = Date(fsTimestamp: UInt64((inode.ctimeExtra << 32) | inode.ctime))\n entry.modificationDate = Date(fsTimestamp: UInt64((inode.mtimeExtra << 32) | inode.mtime))\n entry.contentAccessDate = Date(fsTimestamp: UInt64((inode.atimeExtra << 32) | inode.atime))\n try writer.writeEntry(entry: entry, data: nil)\n }\n try writer.finishEncoding()\n }\n\n @available(*, deprecated, renamed: \"readInlineExtendedAttributes(from:)\")\n public static func readInlineExtenedAttributes(from buffer: [UInt8]) throws -> [EXT4.ExtendedAttribute] {\n try readInlineExtendedAttributes(from: buffer)\n }\n\n public static func readInlineExtendedAttributes(from buffer: [UInt8]) throws -> [EXT4.ExtendedAttribute] {\n let header = UInt32(littleEndian: buffer[0...4].withUnsafeBytes { $0.load(as: UInt32.self) })\n if header != EXT4.XAttrHeaderMagic {\n throw EXT4.FileXattrsState.Error.missingXAttrHeader\n }\n return try EXT4.FileXattrsState.read(buffer: buffer, start: 4, offset: 4)\n }\n\n @available(*, deprecated, renamed: \"readBlockExtendedAttributes(from:)\")\n public static func readBlockExtenedAttributes(from buffer: [UInt8]) throws -> [EXT4.ExtendedAttribute] {\n try readBlockExtendedAttributes(from: buffer)\n }\n\n public static func readBlockExtendedAttributes(from buffer: [UInt8]) throws -> [EXT4.ExtendedAttribute] {\n let header = UInt32(littleEndian: buffer[0...4].withUnsafeBytes { $0.load(as: UInt32.self) })\n if header != EXT4.XAttrHeaderMagic {\n throw EXT4.FileXattrsState.Error.missingXAttrHeader\n }\n\n return try EXT4.FileXattrsState.read(buffer: [UInt8](buffer), start: 32, offset: 0)\n }\n\n func seek(block: UInt32) throws {\n try self.handle.seek(toOffset: UInt64(block) * blockSize)\n }\n}\n\nextension Date {\n init(fsTimestamp: UInt64) {\n if fsTimestamp == 0 {\n self = Date.distantPast\n return\n }\n\n let seconds = Int64(fsTimestamp & 0x3_ffff_ffff)\n let nanoseconds = Double(fsTimestamp >> 34) / 1_000_000_000\n\n self = Date(timeIntervalSince1970: Double(seconds) + nanoseconds)\n }\n}\n#endif\n"], ["/containerization/Sources/ContainerizationOCI/Reference.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\n\nprivate let referenceTotalLengthMax = 255\nprivate let nameTotalLengthMax = 127\nprivate let legacyDockerRegistryHost = \"docker.io\"\nprivate let dockerRegistryHost = \"registry-1.docker.io\"\nprivate let defaultDockerRegistryRepo = \"library\"\nprivate let defaultTag = \"latest\"\n\n/// A Reference is composed of the various parts of an OCI image reference.\n/// For example:\n/// let imageReference = \"my-registry.com/repository/image:tag2\"\n/// let reference = Reference.parse(imageReference)\n/// print(reference.domain!) // gives us \"my-registry.com\"\n/// print(reference.name) // gives us \"my-registry.com/repository/image\"\n/// print(reference.path) // gives us \"repository/image\"\n/// print(reference.tag!) // gives us \"tag2\"\n/// print(reference.digest) // gives us \"nil\"\npublic class Reference: CustomStringConvertible {\n private var _domain: String?\n public var domain: String? {\n _domain\n }\n public var resolvedDomain: String? {\n if let d = _domain {\n return Self.resolveDomain(domain: d)\n }\n return nil\n }\n\n private var _path: String\n public var path: String {\n _path\n }\n\n private var _tag: String?\n public var tag: String? {\n _tag\n }\n\n private var _digest: String?\n public var digest: String? {\n _digest\n }\n\n public var name: String {\n if let domain, !domain.isEmpty {\n return \"\\(domain)/\\(path)\"\n }\n return path\n }\n\n public var description: String {\n if let tag {\n return \"\\(name):\\(tag)\"\n }\n if let digest {\n return \"\\(name)@\\(digest)\"\n }\n return name\n }\n\n static let identifierPattern = \"([a-f0-9]{64})\"\n\n static let domainPattern = {\n let domainNameComponent = \"(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])\"\n let optionalPort = \"(?::[0-9]+)?\"\n let ipv6address = \"\\\\[(?:[a-fA-F0-9:]+)\\\\]\"\n let domainName = \"\\(domainNameComponent)(?:\\\\.\\(domainNameComponent))*\"\n let host = \"(?:\\(domainName)|\\(ipv6address))\"\n let domainAndPort = \"\\(host)\\(optionalPort)\"\n return domainAndPort\n }()\n\n static let pathPattern = \"(?(?:[a-z0-9]+(?:[._]|__|-|/)?)*[a-z0-9]+)\"\n static let tagPattern = \"(?::(?[\\\\w][\\\\w.-]{0,127}))?(?:@(?sha256:[0-9a-fA-F]{64}))?\"\n static let pathTagPattern = \"\\(pathPattern)\\(tagPattern)\"\n\n public init(path: String, domain: String? = nil, tag: String? = nil, digest: String? = nil) throws {\n if let domain, !domain.isEmpty {\n self._domain = domain\n }\n\n self._path = path\n self._tag = tag\n self._digest = digest\n }\n\n public static func parse(_ s: String) throws -> Reference {\n if s.count > referenceTotalLengthMax {\n throw ContainerizationError(.invalidArgument, message: \"Reference length \\(s.count) greater than \\(referenceTotalLengthMax)\")\n }\n\n let identifierRegex = try Regex(Self.identifierPattern)\n guard try identifierRegex.wholeMatch(in: s) == nil else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot specify 64 byte hex string as reference\")\n }\n\n let (domain, remainder) = try Self.parseDomain(from: s)\n let constructedRawReference: String = remainder\n if let domain {\n let domainRegex = try Regex(domainPattern)\n guard try domainRegex.wholeMatch(in: domain) != nil else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid domain \\(domain) for reference \\(s)\")\n }\n }\n let fields = try constructedRawReference.matches(regex: pathTagPattern)\n guard let path = fields[\"path\"] else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot parse path for reference \\(s)\")\n }\n\n let ref = try Reference(path: path, domain: domain)\n if ref.name.count > nameTotalLengthMax {\n throw ContainerizationError(.invalidArgument, message: \"Repo length \\(ref.name.count) greater than \\(nameTotalLengthMax)\")\n }\n\n // Extract tag and digest\n let tag = fields[\"tag\"] ?? \"\"\n let digest = fields[\"digest\"] ?? \"\"\n\n if !digest.isEmpty {\n return try ref.withDigest(digest)\n } else if !tag.isEmpty {\n return try ref.withTag(tag)\n }\n return ref\n }\n\n private static func parseDomain(from s: String) throws -> (domain: String?, remainder: String) {\n var domain: String? = nil\n var path: String = s\n let charset = CharacterSet(charactersIn: \".:\")\n let splits = s.split(separator: \"/\", maxSplits: 1)\n guard splits.count == 2 else {\n if s.starts(with: \"localhost\") {\n return (s, \"\")\n }\n return (nil, s)\n }\n let _domain = String(splits[0])\n let _path = String(splits[1])\n if _domain.starts(with: \"localhost\") || _domain.rangeOfCharacter(from: charset) != nil {\n domain = _domain\n path = _path\n }\n return (domain, path)\n }\n\n public static func withName(_ name: String) throws -> Reference {\n if name.count > nameTotalLengthMax {\n throw ContainerizationError(.invalidArgument, message: \"Name length \\(name.count) greater than \\(nameTotalLengthMax)\")\n }\n let fields = try name.matches(regex: Self.domainPattern)\n // Extract domain and path\n let domain = fields[\"domain\"] ?? \"\"\n let path = fields[\"path\"] ?? \"\"\n\n if domain.isEmpty || path.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Image reference domain or path is empty\")\n }\n\n return try Reference(path: path, domain: domain)\n }\n\n public func withTag(_ tag: String) throws -> Reference {\n var tag = tag\n if !tag.starts(with: \":\") {\n tag = \":\" + tag\n }\n let fields = try tag.matches(regex: Self.tagPattern)\n tag = fields[\"tag\"] ?? \"\"\n\n if tag.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Invalid format for image reference. Missing tag\")\n }\n return try Reference(path: self.path, domain: self.domain, tag: tag)\n }\n\n public func withDigest(_ digest: String) throws -> Reference {\n var digest = digest\n if !digest.starts(with: \"@\") {\n digest = \"@\" + digest\n }\n let fields = try digest.matches(regex: Self.tagPattern)\n digest = fields[\"digest\"] ?? \"\"\n\n if digest.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Invalid format for image reference. Missing digest\")\n }\n return try Reference(path: self.path, domain: self.domain, digest: digest)\n }\n\n private static func splitDomain(_ name: String) -> (domain: String, path: String) {\n let parts = name.split(separator: \"/\")\n guard parts.count == 2 else {\n return (\"\", name)\n }\n return (String(parts[0]), String(parts[1]))\n }\n\n /// Normalize the reference object.\n /// Normalization is useful in cases where the reference object is to be used to\n /// fetch/push an image from/to a remote registry.\n /// It does the following:\n /// - Adds a default tag of \"latest\" if the reference had no tag/digest set.\n /// - If the domain is \"registry-1.docker.io\" or \"docker.io\" and the path has no repository set,\n /// it adds a default \"library/\" repository name.\n public func normalize() {\n if let domain = self.domain, domain == dockerRegistryHost || domain == legacyDockerRegistryHost {\n // Check if the image is being referenced by a named tag.\n // If it is, and a repository is not specified, prefix it with \"library/\".\n // This needs to be done only if we are using the Docker registry.\n if !self.path.contains(\"/\") {\n self._path = \"\\(defaultDockerRegistryRepo)/\\(self._path)\"\n }\n }\n let identifier = self._tag ?? self._digest\n if identifier == nil {\n // If the user did not specify a tag or a digest for the reference, set the tag to \"latest\".\n self._tag = defaultTag\n }\n }\n\n public static func resolveDomain(domain: String) -> String {\n if domain == legacyDockerRegistryHost {\n return dockerRegistryHost\n }\n return domain\n }\n}\n\nextension String {\n func matches(regex: String) throws -> [String: String] {\n do {\n let regex = try NSRegularExpression(pattern: regex, options: [])\n let nsRange = NSRange(self.startIndex.. [String] {\n let pattern = self.pattern\n let regex = try NSRegularExpression(pattern: \"\\\\(\\\\?<(\\\\w+)>\", options: [])\n let nsRange = NSRange(pattern.startIndex.. UnaryCall\n\n func umount(\n _ request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func setenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func getenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func mkdir(\n _ request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func sysctl(\n _ request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func setTime(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func setupEmulator(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func createProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func deleteProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func startProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func killProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func waitProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func resizeProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func closeProcessStdin(\n _ request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func proxyVsock(\n _ request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func stopVsockProxy(\n _ request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func ipLinkSet(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func ipAddrAdd(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func ipRouteAddLink(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func ipRouteAddDefault(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func configureDns(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func configureHosts(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func sync(\n _ request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n\n func kill(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n callOptions: CallOptions?\n ) -> UnaryCall\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextClientProtocol {\n public var serviceName: String {\n return \"com.apple.containerization.sandbox.v3.SandboxContext\"\n }\n\n /// Mount a filesystem.\n ///\n /// - Parameters:\n /// - request: Request to send to Mount.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func mount(\n _ request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMountInterceptors() ?? []\n )\n }\n\n /// Unmount a filesystem.\n ///\n /// - Parameters:\n /// - request: Request to send to Umount.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func umount(\n _ request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.umount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeUmountInterceptors() ?? []\n )\n }\n\n /// Set an environment variable on the init process.\n ///\n /// - Parameters:\n /// - request: Request to send to Setenv.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func setenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetenvInterceptors() ?? []\n )\n }\n\n /// Get an environment variable from the init process.\n ///\n /// - Parameters:\n /// - request: Request to send to Getenv.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func getenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.getenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeGetenvInterceptors() ?? []\n )\n }\n\n /// Create a new directory inside the sandbox.\n ///\n /// - Parameters:\n /// - request: Request to send to Mkdir.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func mkdir(\n _ request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mkdir.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMkdirInterceptors() ?? []\n )\n }\n\n /// Set sysctls in the context of the sandbox.\n ///\n /// - Parameters:\n /// - request: Request to send to Sysctl.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func sysctl(\n _ request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sysctl.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSysctlInterceptors() ?? []\n )\n }\n\n /// Set time in the guest.\n ///\n /// - Parameters:\n /// - request: Request to send to SetTime.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func setTime(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setTime.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetTimeInterceptors() ?? []\n )\n }\n\n /// Set up an emulator in the guest for a specific binary format.\n ///\n /// - Parameters:\n /// - request: Request to send to SetupEmulator.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func setupEmulator(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setupEmulator.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetupEmulatorInterceptors() ?? []\n )\n }\n\n /// Create a new process inside the container.\n ///\n /// - Parameters:\n /// - request: Request to send to CreateProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func createProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.createProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateProcessInterceptors() ?? []\n )\n }\n\n /// Delete an existing process inside the container.\n ///\n /// - Parameters:\n /// - request: Request to send to DeleteProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func deleteProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.deleteProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeDeleteProcessInterceptors() ?? []\n )\n }\n\n /// Start the provided process.\n ///\n /// - Parameters:\n /// - request: Request to send to StartProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func startProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.startProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStartProcessInterceptors() ?? []\n )\n }\n\n /// Send a signal to the provided process.\n ///\n /// - Parameters:\n /// - request: Request to send to KillProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func killProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.killProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillProcessInterceptors() ?? []\n )\n }\n\n /// Wait for a process to exit and return the exit code.\n ///\n /// - Parameters:\n /// - request: Request to send to WaitProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func waitProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.waitProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeWaitProcessInterceptors() ?? []\n )\n }\n\n /// Resize the tty of a given process. This will error if the process does\n /// not have a pty allocated.\n ///\n /// - Parameters:\n /// - request: Request to send to ResizeProcess.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func resizeProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.resizeProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeResizeProcessInterceptors() ?? []\n )\n }\n\n /// Close IO for a given process.\n ///\n /// - Parameters:\n /// - request: Request to send to CloseProcessStdin.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func closeProcessStdin(\n _ request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.closeProcessStdin.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCloseProcessStdinInterceptors() ?? []\n )\n }\n\n /// Proxy a vsock port to a unix domain socket in the guest, or vice versa.\n ///\n /// - Parameters:\n /// - request: Request to send to ProxyVsock.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func proxyVsock(\n _ request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.proxyVsock.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeProxyVsockInterceptors() ?? []\n )\n }\n\n /// Stop a vsock proxy to a unix domain socket.\n ///\n /// - Parameters:\n /// - request: Request to send to StopVsockProxy.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func stopVsockProxy(\n _ request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.stopVsockProxy.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStopVsockProxyInterceptors() ?? []\n )\n }\n\n /// Set the link state of a network interface.\n ///\n /// - Parameters:\n /// - request: Request to send to IpLinkSet.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func ipLinkSet(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipLinkSet.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpLinkSetInterceptors() ?? []\n )\n }\n\n /// Add an IPv4 address to a network interface.\n ///\n /// - Parameters:\n /// - request: Request to send to IpAddrAdd.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func ipAddrAdd(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipAddrAdd.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpAddrAddInterceptors() ?? []\n )\n }\n\n /// Add an IP route for a network interface.\n ///\n /// - Parameters:\n /// - request: Request to send to IpRouteAddLink.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func ipRouteAddLink(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddLink.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddLinkInterceptors() ?? []\n )\n }\n\n /// Add an IP route for a network interface.\n ///\n /// - Parameters:\n /// - request: Request to send to IpRouteAddDefault.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func ipRouteAddDefault(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddDefault.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddDefaultInterceptors() ?? []\n )\n }\n\n /// Configure DNS resolver.\n ///\n /// - Parameters:\n /// - request: Request to send to ConfigureDns.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func configureDns(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureDns.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureDnsInterceptors() ?? []\n )\n }\n\n /// Configure /etc/hosts.\n ///\n /// - Parameters:\n /// - request: Request to send to ConfigureHosts.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func configureHosts(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureHosts.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureHostsInterceptors() ?? []\n )\n }\n\n /// Perform the sync syscall.\n ///\n /// - Parameters:\n /// - request: Request to send to Sync.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func sync(\n _ request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sync.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSyncInterceptors() ?? []\n )\n }\n\n /// Send a signal to a process via the PID.\n ///\n /// - Parameters:\n /// - request: Request to send to Kill.\n /// - callOptions: Call options.\n /// - Returns: A `UnaryCall` with futures for the metadata, status and response.\n public func kill(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n callOptions: CallOptions? = nil\n ) -> UnaryCall {\n return self.makeUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.kill.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillInterceptors() ?? []\n )\n }\n}\n\n@available(*, deprecated)\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextClient: @unchecked Sendable {}\n\n@available(*, deprecated, renamed: \"Com_Apple_Containerization_Sandbox_V3_SandboxContextNIOClient\")\npublic final class Com_Apple_Containerization_Sandbox_V3_SandboxContextClient: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientProtocol {\n private let lock = Lock()\n private var _defaultCallOptions: CallOptions\n private var _interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol?\n public let channel: GRPCChannel\n public var defaultCallOptions: CallOptions {\n get { self.lock.withLock { return self._defaultCallOptions } }\n set { self.lock.withLockVoid { self._defaultCallOptions = newValue } }\n }\n public var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? {\n get { self.lock.withLock { return self._interceptors } }\n set { self.lock.withLockVoid { self._interceptors = newValue } }\n }\n\n /// Creates a client for the com.apple.containerization.sandbox.v3.SandboxContext service.\n ///\n /// - Parameters:\n /// - channel: `GRPCChannel` to the service host.\n /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them.\n /// - interceptors: A factory providing interceptors for each RPC.\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self._defaultCallOptions = defaultCallOptions\n self._interceptors = interceptors\n }\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SandboxContextNIOClient: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientProtocol {\n public var channel: GRPCChannel\n public var defaultCallOptions: CallOptions\n public var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol?\n\n /// Creates a client for the com.apple.containerization.sandbox.v3.SandboxContext service.\n ///\n /// - Parameters:\n /// - channel: `GRPCChannel` to the service host.\n /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them.\n /// - interceptors: A factory providing interceptors for each RPC.\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self.defaultCallOptions = defaultCallOptions\n self.interceptors = interceptors\n }\n}\n\n/// Context for interacting with a container's runtime environment.\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClientProtocol: GRPCClient {\n static var serviceDescriptor: GRPCServiceDescriptor { get }\n var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? { get }\n\n func makeMountCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeUmountCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeSetenvCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeGetenvCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeMkdirCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeSysctlCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeSetTimeCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeSetupEmulatorCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeCreateProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeDeleteProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeStartProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeKillProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeWaitProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeResizeProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeCloseProcessStdinCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeProxyVsockCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeStopVsockProxyCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeIpLinkSetCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeIpAddrAddCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeIpRouteAddLinkCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeIpRouteAddDefaultCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeConfigureDnsCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeConfigureHostsCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeSyncCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n\n func makeKillCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n callOptions: CallOptions?\n ) -> GRPCAsyncUnaryCall\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClientProtocol {\n public static var serviceDescriptor: GRPCServiceDescriptor {\n return Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.serviceDescriptor\n }\n\n public var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? {\n return nil\n }\n\n public func makeMountCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMountInterceptors() ?? []\n )\n }\n\n public func makeUmountCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.umount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeUmountInterceptors() ?? []\n )\n }\n\n public func makeSetenvCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetenvInterceptors() ?? []\n )\n }\n\n public func makeGetenvCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.getenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeGetenvInterceptors() ?? []\n )\n }\n\n public func makeMkdirCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mkdir.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMkdirInterceptors() ?? []\n )\n }\n\n public func makeSysctlCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sysctl.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSysctlInterceptors() ?? []\n )\n }\n\n public func makeSetTimeCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setTime.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetTimeInterceptors() ?? []\n )\n }\n\n public func makeSetupEmulatorCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setupEmulator.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetupEmulatorInterceptors() ?? []\n )\n }\n\n public func makeCreateProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.createProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateProcessInterceptors() ?? []\n )\n }\n\n public func makeDeleteProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.deleteProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeDeleteProcessInterceptors() ?? []\n )\n }\n\n public func makeStartProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.startProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStartProcessInterceptors() ?? []\n )\n }\n\n public func makeKillProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.killProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillProcessInterceptors() ?? []\n )\n }\n\n public func makeWaitProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.waitProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeWaitProcessInterceptors() ?? []\n )\n }\n\n public func makeResizeProcessCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.resizeProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeResizeProcessInterceptors() ?? []\n )\n }\n\n public func makeCloseProcessStdinCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.closeProcessStdin.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCloseProcessStdinInterceptors() ?? []\n )\n }\n\n public func makeProxyVsockCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.proxyVsock.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeProxyVsockInterceptors() ?? []\n )\n }\n\n public func makeStopVsockProxyCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.stopVsockProxy.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStopVsockProxyInterceptors() ?? []\n )\n }\n\n public func makeIpLinkSetCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipLinkSet.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpLinkSetInterceptors() ?? []\n )\n }\n\n public func makeIpAddrAddCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipAddrAdd.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpAddrAddInterceptors() ?? []\n )\n }\n\n public func makeIpRouteAddLinkCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddLink.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddLinkInterceptors() ?? []\n )\n }\n\n public func makeIpRouteAddDefaultCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddDefault.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddDefaultInterceptors() ?? []\n )\n }\n\n public func makeConfigureDnsCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureDns.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureDnsInterceptors() ?? []\n )\n }\n\n public func makeConfigureHostsCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureHosts.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureHostsInterceptors() ?? []\n )\n }\n\n public func makeSyncCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sync.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSyncInterceptors() ?? []\n )\n }\n\n public func makeKillCall(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n callOptions: CallOptions? = nil\n ) -> GRPCAsyncUnaryCall {\n return self.makeAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.kill.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillInterceptors() ?? []\n )\n }\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClientProtocol {\n public func mount(\n _ request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_MountResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMountInterceptors() ?? []\n )\n }\n\n public func umount(\n _ request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_UmountResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.umount.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeUmountInterceptors() ?? []\n )\n }\n\n public func setenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetenvResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetenvInterceptors() ?? []\n )\n }\n\n public func getenv(\n _ request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_GetenvResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.getenv.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeGetenvInterceptors() ?? []\n )\n }\n\n public func mkdir(\n _ request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_MkdirResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mkdir.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeMkdirInterceptors() ?? []\n )\n }\n\n public func sysctl(\n _ request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SysctlResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sysctl.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSysctlInterceptors() ?? []\n )\n }\n\n public func setTime(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetTimeResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setTime.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetTimeInterceptors() ?? []\n )\n }\n\n public func setupEmulator(\n _ request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setupEmulator.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSetupEmulatorInterceptors() ?? []\n )\n }\n\n public func createProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.createProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCreateProcessInterceptors() ?? []\n )\n }\n\n public func deleteProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.deleteProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeDeleteProcessInterceptors() ?? []\n )\n }\n\n public func startProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StartProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.startProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStartProcessInterceptors() ?? []\n )\n }\n\n public func killProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.killProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillProcessInterceptors() ?? []\n )\n }\n\n public func waitProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.waitProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeWaitProcessInterceptors() ?? []\n )\n }\n\n public func resizeProcess(\n _ request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.resizeProcess.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeResizeProcessInterceptors() ?? []\n )\n }\n\n public func closeProcessStdin(\n _ request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.closeProcessStdin.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeCloseProcessStdinInterceptors() ?? []\n )\n }\n\n public func proxyVsock(\n _ request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.proxyVsock.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeProxyVsockInterceptors() ?? []\n )\n }\n\n public func stopVsockProxy(\n _ request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.stopVsockProxy.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeStopVsockProxyInterceptors() ?? []\n )\n }\n\n public func ipLinkSet(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipLinkSet.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpLinkSetInterceptors() ?? []\n )\n }\n\n public func ipAddrAdd(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipAddrAdd.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpAddrAddInterceptors() ?? []\n )\n }\n\n public func ipRouteAddLink(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddLink.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddLinkInterceptors() ?? []\n )\n }\n\n public func ipRouteAddDefault(\n _ request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddDefault.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeIpRouteAddDefaultInterceptors() ?? []\n )\n }\n\n public func configureDns(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureDns.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureDnsInterceptors() ?? []\n )\n }\n\n public func configureHosts(\n _ request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureHosts.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeConfigureHostsInterceptors() ?? []\n )\n }\n\n public func sync(\n _ request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SyncResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sync.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeSyncInterceptors() ?? []\n )\n }\n\n public func kill(\n _ request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n callOptions: CallOptions? = nil\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillResponse {\n return try await self.performAsyncUnaryCall(\n path: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.kill.path,\n request: request,\n callOptions: callOptions ?? self.defaultCallOptions,\n interceptors: self.interceptors?.makeKillInterceptors() ?? []\n )\n }\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic struct Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClient: Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncClientProtocol {\n public var channel: GRPCChannel\n public var defaultCallOptions: CallOptions\n public var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol?\n\n public init(\n channel: GRPCChannel,\n defaultCallOptions: CallOptions = CallOptions(),\n interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol? = nil\n ) {\n self.channel = channel\n self.defaultCallOptions = defaultCallOptions\n self.interceptors = interceptors\n }\n}\n\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextClientInterceptorFactoryProtocol: Sendable {\n\n /// - Returns: Interceptors to use when invoking 'mount'.\n func makeMountInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'umount'.\n func makeUmountInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'setenv'.\n func makeSetenvInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'getenv'.\n func makeGetenvInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'mkdir'.\n func makeMkdirInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'sysctl'.\n func makeSysctlInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'setTime'.\n func makeSetTimeInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'setupEmulator'.\n func makeSetupEmulatorInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'createProcess'.\n func makeCreateProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'deleteProcess'.\n func makeDeleteProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'startProcess'.\n func makeStartProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'killProcess'.\n func makeKillProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'waitProcess'.\n func makeWaitProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'resizeProcess'.\n func makeResizeProcessInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'closeProcessStdin'.\n func makeCloseProcessStdinInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'proxyVsock'.\n func makeProxyVsockInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'stopVsockProxy'.\n func makeStopVsockProxyInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'ipLinkSet'.\n func makeIpLinkSetInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'ipAddrAdd'.\n func makeIpAddrAddInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'ipRouteAddLink'.\n func makeIpRouteAddLinkInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'ipRouteAddDefault'.\n func makeIpRouteAddDefaultInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'configureDns'.\n func makeConfigureDnsInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'configureHosts'.\n func makeConfigureHostsInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'sync'.\n func makeSyncInterceptors() -> [ClientInterceptor]\n\n /// - Returns: Interceptors to use when invoking 'kill'.\n func makeKillInterceptors() -> [ClientInterceptor]\n}\n\npublic enum Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata {\n public static let serviceDescriptor = GRPCServiceDescriptor(\n name: \"SandboxContext\",\n fullName: \"com.apple.containerization.sandbox.v3.SandboxContext\",\n methods: [\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mount,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.umount,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setenv,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.getenv,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.mkdir,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sysctl,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setTime,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.setupEmulator,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.createProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.deleteProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.startProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.killProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.waitProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.resizeProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.closeProcessStdin,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.proxyVsock,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.stopVsockProxy,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipLinkSet,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipAddrAdd,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddLink,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.ipRouteAddDefault,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureDns,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.configureHosts,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.sync,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextClientMetadata.Methods.kill,\n ]\n )\n\n public enum Methods {\n public static let mount = GRPCMethodDescriptor(\n name: \"Mount\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Mount\",\n type: GRPCCallType.unary\n )\n\n public static let umount = GRPCMethodDescriptor(\n name: \"Umount\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Umount\",\n type: GRPCCallType.unary\n )\n\n public static let setenv = GRPCMethodDescriptor(\n name: \"Setenv\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Setenv\",\n type: GRPCCallType.unary\n )\n\n public static let getenv = GRPCMethodDescriptor(\n name: \"Getenv\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Getenv\",\n type: GRPCCallType.unary\n )\n\n public static let mkdir = GRPCMethodDescriptor(\n name: \"Mkdir\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Mkdir\",\n type: GRPCCallType.unary\n )\n\n public static let sysctl = GRPCMethodDescriptor(\n name: \"Sysctl\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Sysctl\",\n type: GRPCCallType.unary\n )\n\n public static let setTime = GRPCMethodDescriptor(\n name: \"SetTime\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/SetTime\",\n type: GRPCCallType.unary\n )\n\n public static let setupEmulator = GRPCMethodDescriptor(\n name: \"SetupEmulator\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/SetupEmulator\",\n type: GRPCCallType.unary\n )\n\n public static let createProcess = GRPCMethodDescriptor(\n name: \"CreateProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/CreateProcess\",\n type: GRPCCallType.unary\n )\n\n public static let deleteProcess = GRPCMethodDescriptor(\n name: \"DeleteProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/DeleteProcess\",\n type: GRPCCallType.unary\n )\n\n public static let startProcess = GRPCMethodDescriptor(\n name: \"StartProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/StartProcess\",\n type: GRPCCallType.unary\n )\n\n public static let killProcess = GRPCMethodDescriptor(\n name: \"KillProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/KillProcess\",\n type: GRPCCallType.unary\n )\n\n public static let waitProcess = GRPCMethodDescriptor(\n name: \"WaitProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/WaitProcess\",\n type: GRPCCallType.unary\n )\n\n public static let resizeProcess = GRPCMethodDescriptor(\n name: \"ResizeProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ResizeProcess\",\n type: GRPCCallType.unary\n )\n\n public static let closeProcessStdin = GRPCMethodDescriptor(\n name: \"CloseProcessStdin\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/CloseProcessStdin\",\n type: GRPCCallType.unary\n )\n\n public static let proxyVsock = GRPCMethodDescriptor(\n name: \"ProxyVsock\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ProxyVsock\",\n type: GRPCCallType.unary\n )\n\n public static let stopVsockProxy = GRPCMethodDescriptor(\n name: \"StopVsockProxy\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/StopVsockProxy\",\n type: GRPCCallType.unary\n )\n\n public static let ipLinkSet = GRPCMethodDescriptor(\n name: \"IpLinkSet\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpLinkSet\",\n type: GRPCCallType.unary\n )\n\n public static let ipAddrAdd = GRPCMethodDescriptor(\n name: \"IpAddrAdd\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpAddrAdd\",\n type: GRPCCallType.unary\n )\n\n public static let ipRouteAddLink = GRPCMethodDescriptor(\n name: \"IpRouteAddLink\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpRouteAddLink\",\n type: GRPCCallType.unary\n )\n\n public static let ipRouteAddDefault = GRPCMethodDescriptor(\n name: \"IpRouteAddDefault\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpRouteAddDefault\",\n type: GRPCCallType.unary\n )\n\n public static let configureDns = GRPCMethodDescriptor(\n name: \"ConfigureDns\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ConfigureDns\",\n type: GRPCCallType.unary\n )\n\n public static let configureHosts = GRPCMethodDescriptor(\n name: \"ConfigureHosts\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ConfigureHosts\",\n type: GRPCCallType.unary\n )\n\n public static let sync = GRPCMethodDescriptor(\n name: \"Sync\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Sync\",\n type: GRPCCallType.unary\n )\n\n public static let kill = GRPCMethodDescriptor(\n name: \"Kill\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Kill\",\n type: GRPCCallType.unary\n )\n }\n}\n\n/// Context for interacting with a container's runtime environment.\n///\n/// To build a server, implement a class that conforms to this protocol.\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextProvider: CallHandlerProvider {\n var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextServerInterceptorFactoryProtocol? { get }\n\n /// Mount a filesystem.\n func mount(request: Com_Apple_Containerization_Sandbox_V3_MountRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Unmount a filesystem.\n func umount(request: Com_Apple_Containerization_Sandbox_V3_UmountRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Set an environment variable on the init process.\n func setenv(request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Get an environment variable from the init process.\n func getenv(request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Create a new directory inside the sandbox.\n func mkdir(request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Set sysctls in the context of the sandbox.\n func sysctl(request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Set time in the guest.\n func setTime(request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Set up an emulator in the guest for a specific binary format.\n func setupEmulator(request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Create a new process inside the container.\n func createProcess(request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Delete an existing process inside the container.\n func deleteProcess(request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Start the provided process.\n func startProcess(request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Send a signal to the provided process.\n func killProcess(request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Wait for a process to exit and return the exit code.\n func waitProcess(request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Resize the tty of a given process. This will error if the process does\n /// not have a pty allocated.\n func resizeProcess(request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Close IO for a given process.\n func closeProcessStdin(request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Proxy a vsock port to a unix domain socket in the guest, or vice versa.\n func proxyVsock(request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Stop a vsock proxy to a unix domain socket.\n func stopVsockProxy(request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Set the link state of a network interface.\n func ipLinkSet(request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Add an IPv4 address to a network interface.\n func ipAddrAdd(request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Add an IP route for a network interface.\n func ipRouteAddLink(request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Add an IP route for a network interface.\n func ipRouteAddDefault(request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Configure DNS resolver.\n func configureDns(request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Configure /etc/hosts.\n func configureHosts(request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Perform the sync syscall.\n func sync(request: Com_Apple_Containerization_Sandbox_V3_SyncRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n\n /// Send a signal to a process via the PID.\n func kill(request: Com_Apple_Containerization_Sandbox_V3_KillRequest, context: StatusOnlyCallContext) -> EventLoopFuture\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextProvider {\n public var serviceName: Substring {\n return Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.serviceDescriptor.fullName[...]\n }\n\n /// Determines, calls and returns the appropriate request handler, depending on the request's method.\n /// Returns nil for methods not handled by this service.\n public func handle(\n method name: Substring,\n context: CallHandlerContext\n ) -> GRPCServerHandlerProtocol? {\n switch name {\n case \"Mount\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeMountInterceptors() ?? [],\n userFunction: self.mount(request:context:)\n )\n\n case \"Umount\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeUmountInterceptors() ?? [],\n userFunction: self.umount(request:context:)\n )\n\n case \"Setenv\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetenvInterceptors() ?? [],\n userFunction: self.setenv(request:context:)\n )\n\n case \"Getenv\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeGetenvInterceptors() ?? [],\n userFunction: self.getenv(request:context:)\n )\n\n case \"Mkdir\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeMkdirInterceptors() ?? [],\n userFunction: self.mkdir(request:context:)\n )\n\n case \"Sysctl\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSysctlInterceptors() ?? [],\n userFunction: self.sysctl(request:context:)\n )\n\n case \"SetTime\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetTimeInterceptors() ?? [],\n userFunction: self.setTime(request:context:)\n )\n\n case \"SetupEmulator\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetupEmulatorInterceptors() ?? [],\n userFunction: self.setupEmulator(request:context:)\n )\n\n case \"CreateProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCreateProcessInterceptors() ?? [],\n userFunction: self.createProcess(request:context:)\n )\n\n case \"DeleteProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeDeleteProcessInterceptors() ?? [],\n userFunction: self.deleteProcess(request:context:)\n )\n\n case \"StartProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeStartProcessInterceptors() ?? [],\n userFunction: self.startProcess(request:context:)\n )\n\n case \"KillProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeKillProcessInterceptors() ?? [],\n userFunction: self.killProcess(request:context:)\n )\n\n case \"WaitProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeWaitProcessInterceptors() ?? [],\n userFunction: self.waitProcess(request:context:)\n )\n\n case \"ResizeProcess\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeResizeProcessInterceptors() ?? [],\n userFunction: self.resizeProcess(request:context:)\n )\n\n case \"CloseProcessStdin\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCloseProcessStdinInterceptors() ?? [],\n userFunction: self.closeProcessStdin(request:context:)\n )\n\n case \"ProxyVsock\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeProxyVsockInterceptors() ?? [],\n userFunction: self.proxyVsock(request:context:)\n )\n\n case \"StopVsockProxy\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeStopVsockProxyInterceptors() ?? [],\n userFunction: self.stopVsockProxy(request:context:)\n )\n\n case \"IpLinkSet\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpLinkSetInterceptors() ?? [],\n userFunction: self.ipLinkSet(request:context:)\n )\n\n case \"IpAddrAdd\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpAddrAddInterceptors() ?? [],\n userFunction: self.ipAddrAdd(request:context:)\n )\n\n case \"IpRouteAddLink\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpRouteAddLinkInterceptors() ?? [],\n userFunction: self.ipRouteAddLink(request:context:)\n )\n\n case \"IpRouteAddDefault\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpRouteAddDefaultInterceptors() ?? [],\n userFunction: self.ipRouteAddDefault(request:context:)\n )\n\n case \"ConfigureDns\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeConfigureDnsInterceptors() ?? [],\n userFunction: self.configureDns(request:context:)\n )\n\n case \"ConfigureHosts\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeConfigureHostsInterceptors() ?? [],\n userFunction: self.configureHosts(request:context:)\n )\n\n case \"Sync\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSyncInterceptors() ?? [],\n userFunction: self.sync(request:context:)\n )\n\n case \"Kill\":\n return UnaryServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeKillInterceptors() ?? [],\n userFunction: self.kill(request:context:)\n )\n\n default:\n return nil\n }\n }\n}\n\n/// Context for interacting with a container's runtime environment.\n///\n/// To implement a server, implement an object which conforms to this protocol.\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncProvider: CallHandlerProvider, Sendable {\n static var serviceDescriptor: GRPCServiceDescriptor { get }\n var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextServerInterceptorFactoryProtocol? { get }\n\n /// Mount a filesystem.\n func mount(\n request: Com_Apple_Containerization_Sandbox_V3_MountRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_MountResponse\n\n /// Unmount a filesystem.\n func umount(\n request: Com_Apple_Containerization_Sandbox_V3_UmountRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_UmountResponse\n\n /// Set an environment variable on the init process.\n func setenv(\n request: Com_Apple_Containerization_Sandbox_V3_SetenvRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetenvResponse\n\n /// Get an environment variable from the init process.\n func getenv(\n request: Com_Apple_Containerization_Sandbox_V3_GetenvRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_GetenvResponse\n\n /// Create a new directory inside the sandbox.\n func mkdir(\n request: Com_Apple_Containerization_Sandbox_V3_MkdirRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_MkdirResponse\n\n /// Set sysctls in the context of the sandbox.\n func sysctl(\n request: Com_Apple_Containerization_Sandbox_V3_SysctlRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SysctlResponse\n\n /// Set time in the guest.\n func setTime(\n request: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetTimeResponse\n\n /// Set up an emulator in the guest for a specific binary format.\n func setupEmulator(\n request: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse\n\n /// Create a new process inside the container.\n func createProcess(\n request: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse\n\n /// Delete an existing process inside the container.\n func deleteProcess(\n request: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse\n\n /// Start the provided process.\n func startProcess(\n request: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StartProcessResponse\n\n /// Send a signal to the provided process.\n func killProcess(\n request: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillProcessResponse\n\n /// Wait for a process to exit and return the exit code.\n func waitProcess(\n request: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse\n\n /// Resize the tty of a given process. This will error if the process does\n /// not have a pty allocated.\n func resizeProcess(\n request: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse\n\n /// Close IO for a given process.\n func closeProcessStdin(\n request: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse\n\n /// Proxy a vsock port to a unix domain socket in the guest, or vice versa.\n func proxyVsock(\n request: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse\n\n /// Stop a vsock proxy to a unix domain socket.\n func stopVsockProxy(\n request: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse\n\n /// Set the link state of a network interface.\n func ipLinkSet(\n request: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse\n\n /// Add an IPv4 address to a network interface.\n func ipAddrAdd(\n request: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse\n\n /// Add an IP route for a network interface.\n func ipRouteAddLink(\n request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse\n\n /// Add an IP route for a network interface.\n func ipRouteAddDefault(\n request: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse\n\n /// Configure DNS resolver.\n func configureDns(\n request: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse\n\n /// Configure /etc/hosts.\n func configureHosts(\n request: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse\n\n /// Perform the sync syscall.\n func sync(\n request: Com_Apple_Containerization_Sandbox_V3_SyncRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_SyncResponse\n\n /// Send a signal to a process via the PID.\n func kill(\n request: Com_Apple_Containerization_Sandbox_V3_KillRequest,\n context: GRPCAsyncServerCallContext\n ) async throws -> Com_Apple_Containerization_Sandbox_V3_KillResponse\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nextension Com_Apple_Containerization_Sandbox_V3_SandboxContextAsyncProvider {\n public static var serviceDescriptor: GRPCServiceDescriptor {\n return Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.serviceDescriptor\n }\n\n public var serviceName: Substring {\n return Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.serviceDescriptor.fullName[...]\n }\n\n public var interceptors: Com_Apple_Containerization_Sandbox_V3_SandboxContextServerInterceptorFactoryProtocol? {\n return nil\n }\n\n public func handle(\n method name: Substring,\n context: CallHandlerContext\n ) -> GRPCServerHandlerProtocol? {\n switch name {\n case \"Mount\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeMountInterceptors() ?? [],\n wrapping: { try await self.mount(request: $0, context: $1) }\n )\n\n case \"Umount\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeUmountInterceptors() ?? [],\n wrapping: { try await self.umount(request: $0, context: $1) }\n )\n\n case \"Setenv\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetenvInterceptors() ?? [],\n wrapping: { try await self.setenv(request: $0, context: $1) }\n )\n\n case \"Getenv\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeGetenvInterceptors() ?? [],\n wrapping: { try await self.getenv(request: $0, context: $1) }\n )\n\n case \"Mkdir\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeMkdirInterceptors() ?? [],\n wrapping: { try await self.mkdir(request: $0, context: $1) }\n )\n\n case \"Sysctl\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSysctlInterceptors() ?? [],\n wrapping: { try await self.sysctl(request: $0, context: $1) }\n )\n\n case \"SetTime\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetTimeInterceptors() ?? [],\n wrapping: { try await self.setTime(request: $0, context: $1) }\n )\n\n case \"SetupEmulator\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSetupEmulatorInterceptors() ?? [],\n wrapping: { try await self.setupEmulator(request: $0, context: $1) }\n )\n\n case \"CreateProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCreateProcessInterceptors() ?? [],\n wrapping: { try await self.createProcess(request: $0, context: $1) }\n )\n\n case \"DeleteProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeDeleteProcessInterceptors() ?? [],\n wrapping: { try await self.deleteProcess(request: $0, context: $1) }\n )\n\n case \"StartProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeStartProcessInterceptors() ?? [],\n wrapping: { try await self.startProcess(request: $0, context: $1) }\n )\n\n case \"KillProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeKillProcessInterceptors() ?? [],\n wrapping: { try await self.killProcess(request: $0, context: $1) }\n )\n\n case \"WaitProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeWaitProcessInterceptors() ?? [],\n wrapping: { try await self.waitProcess(request: $0, context: $1) }\n )\n\n case \"ResizeProcess\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeResizeProcessInterceptors() ?? [],\n wrapping: { try await self.resizeProcess(request: $0, context: $1) }\n )\n\n case \"CloseProcessStdin\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeCloseProcessStdinInterceptors() ?? [],\n wrapping: { try await self.closeProcessStdin(request: $0, context: $1) }\n )\n\n case \"ProxyVsock\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeProxyVsockInterceptors() ?? [],\n wrapping: { try await self.proxyVsock(request: $0, context: $1) }\n )\n\n case \"StopVsockProxy\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeStopVsockProxyInterceptors() ?? [],\n wrapping: { try await self.stopVsockProxy(request: $0, context: $1) }\n )\n\n case \"IpLinkSet\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpLinkSetInterceptors() ?? [],\n wrapping: { try await self.ipLinkSet(request: $0, context: $1) }\n )\n\n case \"IpAddrAdd\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpAddrAddInterceptors() ?? [],\n wrapping: { try await self.ipAddrAdd(request: $0, context: $1) }\n )\n\n case \"IpRouteAddLink\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpRouteAddLinkInterceptors() ?? [],\n wrapping: { try await self.ipRouteAddLink(request: $0, context: $1) }\n )\n\n case \"IpRouteAddDefault\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeIpRouteAddDefaultInterceptors() ?? [],\n wrapping: { try await self.ipRouteAddDefault(request: $0, context: $1) }\n )\n\n case \"ConfigureDns\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeConfigureDnsInterceptors() ?? [],\n wrapping: { try await self.configureDns(request: $0, context: $1) }\n )\n\n case \"ConfigureHosts\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeConfigureHostsInterceptors() ?? [],\n wrapping: { try await self.configureHosts(request: $0, context: $1) }\n )\n\n case \"Sync\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeSyncInterceptors() ?? [],\n wrapping: { try await self.sync(request: $0, context: $1) }\n )\n\n case \"Kill\":\n return GRPCAsyncServerHandler(\n context: context,\n requestDeserializer: ProtobufDeserializer(),\n responseSerializer: ProtobufSerializer(),\n interceptors: self.interceptors?.makeKillInterceptors() ?? [],\n wrapping: { try await self.kill(request: $0, context: $1) }\n )\n\n default:\n return nil\n }\n }\n}\n\npublic protocol Com_Apple_Containerization_Sandbox_V3_SandboxContextServerInterceptorFactoryProtocol: Sendable {\n\n /// - Returns: Interceptors to use when handling 'mount'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeMountInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'umount'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeUmountInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'setenv'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeSetenvInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'getenv'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeGetenvInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'mkdir'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeMkdirInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'sysctl'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeSysctlInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'setTime'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeSetTimeInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'setupEmulator'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeSetupEmulatorInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'createProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeCreateProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'deleteProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeDeleteProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'startProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeStartProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'killProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeKillProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'waitProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeWaitProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'resizeProcess'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeResizeProcessInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'closeProcessStdin'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeCloseProcessStdinInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'proxyVsock'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeProxyVsockInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'stopVsockProxy'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeStopVsockProxyInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'ipLinkSet'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeIpLinkSetInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'ipAddrAdd'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeIpAddrAddInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'ipRouteAddLink'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeIpRouteAddLinkInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'ipRouteAddDefault'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeIpRouteAddDefaultInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'configureDns'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeConfigureDnsInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'configureHosts'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeConfigureHostsInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'sync'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeSyncInterceptors() -> [ServerInterceptor]\n\n /// - Returns: Interceptors to use when handling 'kill'.\n /// Defaults to calling `self.makeInterceptors()`.\n func makeKillInterceptors() -> [ServerInterceptor]\n}\n\npublic enum Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata {\n public static let serviceDescriptor = GRPCServiceDescriptor(\n name: \"SandboxContext\",\n fullName: \"com.apple.containerization.sandbox.v3.SandboxContext\",\n methods: [\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.mount,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.umount,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.setenv,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.getenv,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.mkdir,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.sysctl,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.setTime,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.setupEmulator,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.createProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.deleteProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.startProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.killProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.waitProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.resizeProcess,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.closeProcessStdin,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.proxyVsock,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.stopVsockProxy,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.ipLinkSet,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.ipAddrAdd,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.ipRouteAddLink,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.ipRouteAddDefault,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.configureDns,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.configureHosts,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.sync,\n Com_Apple_Containerization_Sandbox_V3_SandboxContextServerMetadata.Methods.kill,\n ]\n )\n\n public enum Methods {\n public static let mount = GRPCMethodDescriptor(\n name: \"Mount\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Mount\",\n type: GRPCCallType.unary\n )\n\n public static let umount = GRPCMethodDescriptor(\n name: \"Umount\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Umount\",\n type: GRPCCallType.unary\n )\n\n public static let setenv = GRPCMethodDescriptor(\n name: \"Setenv\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Setenv\",\n type: GRPCCallType.unary\n )\n\n public static let getenv = GRPCMethodDescriptor(\n name: \"Getenv\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Getenv\",\n type: GRPCCallType.unary\n )\n\n public static let mkdir = GRPCMethodDescriptor(\n name: \"Mkdir\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Mkdir\",\n type: GRPCCallType.unary\n )\n\n public static let sysctl = GRPCMethodDescriptor(\n name: \"Sysctl\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Sysctl\",\n type: GRPCCallType.unary\n )\n\n public static let setTime = GRPCMethodDescriptor(\n name: \"SetTime\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/SetTime\",\n type: GRPCCallType.unary\n )\n\n public static let setupEmulator = GRPCMethodDescriptor(\n name: \"SetupEmulator\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/SetupEmulator\",\n type: GRPCCallType.unary\n )\n\n public static let createProcess = GRPCMethodDescriptor(\n name: \"CreateProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/CreateProcess\",\n type: GRPCCallType.unary\n )\n\n public static let deleteProcess = GRPCMethodDescriptor(\n name: \"DeleteProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/DeleteProcess\",\n type: GRPCCallType.unary\n )\n\n public static let startProcess = GRPCMethodDescriptor(\n name: \"StartProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/StartProcess\",\n type: GRPCCallType.unary\n )\n\n public static let killProcess = GRPCMethodDescriptor(\n name: \"KillProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/KillProcess\",\n type: GRPCCallType.unary\n )\n\n public static let waitProcess = GRPCMethodDescriptor(\n name: \"WaitProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/WaitProcess\",\n type: GRPCCallType.unary\n )\n\n public static let resizeProcess = GRPCMethodDescriptor(\n name: \"ResizeProcess\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ResizeProcess\",\n type: GRPCCallType.unary\n )\n\n public static let closeProcessStdin = GRPCMethodDescriptor(\n name: \"CloseProcessStdin\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/CloseProcessStdin\",\n type: GRPCCallType.unary\n )\n\n public static let proxyVsock = GRPCMethodDescriptor(\n name: \"ProxyVsock\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ProxyVsock\",\n type: GRPCCallType.unary\n )\n\n public static let stopVsockProxy = GRPCMethodDescriptor(\n name: \"StopVsockProxy\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/StopVsockProxy\",\n type: GRPCCallType.unary\n )\n\n public static let ipLinkSet = GRPCMethodDescriptor(\n name: \"IpLinkSet\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpLinkSet\",\n type: GRPCCallType.unary\n )\n\n public static let ipAddrAdd = GRPCMethodDescriptor(\n name: \"IpAddrAdd\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpAddrAdd\",\n type: GRPCCallType.unary\n )\n\n public static let ipRouteAddLink = GRPCMethodDescriptor(\n name: \"IpRouteAddLink\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpRouteAddLink\",\n type: GRPCCallType.unary\n )\n\n public static let ipRouteAddDefault = GRPCMethodDescriptor(\n name: \"IpRouteAddDefault\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/IpRouteAddDefault\",\n type: GRPCCallType.unary\n )\n\n public static let configureDns = GRPCMethodDescriptor(\n name: \"ConfigureDns\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ConfigureDns\",\n type: GRPCCallType.unary\n )\n\n public static let configureHosts = GRPCMethodDescriptor(\n name: \"ConfigureHosts\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/ConfigureHosts\",\n type: GRPCCallType.unary\n )\n\n public static let sync = GRPCMethodDescriptor(\n name: \"Sync\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Sync\",\n type: GRPCCallType.unary\n )\n\n public static let kill = GRPCMethodDescriptor(\n name: \"Kill\",\n path: \"/com.apple.containerization.sandbox.v3.SandboxContext/Kill\",\n type: GRPCCallType.unary\n )\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/FilePath+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\nextension FilePath {\n public static let Separator: String = \"/\"\n\n public var bytes: [UInt8] {\n self.withCString { cstr in\n var ptr = cstr\n var rawBytes: [UInt8] = []\n while UInt(bitPattern: ptr) != 0 {\n if ptr.pointee == 0x00 { break }\n rawBytes.append(UInt8(bitPattern: ptr.pointee))\n ptr = ptr.successor()\n }\n return rawBytes\n }\n }\n\n public var base: String {\n self.lastComponent?.string ?? \"/\"\n }\n\n public var dir: FilePath {\n self.removingLastComponent()\n }\n\n public var url: URL {\n URL(fileURLWithPath: self.string)\n }\n\n public var items: [String] {\n self.components.map { $0.string }\n }\n\n public init(_ url: URL) {\n self.init(url.path(percentEncoded: false))\n }\n\n public init?(_ data: Data) {\n let cstr: String? = data.withUnsafeBytes { (rbp: UnsafeRawBufferPointer) in\n guard let baseAddress = rbp.baseAddress else {\n return nil\n }\n\n let cString = baseAddress.bindMemory(to: CChar.self, capacity: data.count)\n return String(cString: cString)\n }\n\n guard let cstr else {\n return nil\n }\n self.init(cstr)\n }\n\n public func join(_ path: FilePath) -> FilePath {\n self.pushing(path)\n }\n\n public func join(_ path: String) -> FilePath {\n self.join(FilePath(path))\n }\n\n public func split() -> (dir: FilePath, base: String) {\n (self.dir, self.base)\n }\n\n public func clean() -> FilePath {\n self.lexicallyNormalized()\n }\n\n public static func rel(_ basepath: String, _ targpath: String) -> FilePath {\n let base = FilePath(basepath)\n let targ = FilePath(targpath)\n\n if base == targ {\n return \".\"\n }\n\n let baseComponents = base.items\n let targComponents = targ.items\n\n var commonPrefix = 0\n while commonPrefix < min(baseComponents.count, targComponents.count)\n && baseComponents[commonPrefix] == targComponents[commonPrefix]\n {\n commonPrefix += 1\n }\n\n let upCount = baseComponents.count - commonPrefix\n let relComponents = Array(repeating: \"..\", count: upCount) + targComponents[commonPrefix...]\n\n return FilePath(relComponents.joined(separator: Self.Separator))\n }\n}\n\nextension FileHandle {\n public convenience init?(forWritingTo path: FilePath) {\n self.init(forWritingAtPath: path.description)\n }\n\n public convenience init?(forReadingAtPath path: FilePath) {\n self.init(forReadingAtPath: path.description)\n }\n\n public convenience init?(forReadingFrom path: FilePath) {\n self.init(forReadingAtPath: path.description)\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Platform.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// Source: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/config.go\n\nimport ContainerizationError\nimport Foundation\n\n/// Platform describes the platform which the image in the manifest runs on.\npublic struct Platform: Sendable, Equatable {\n public static var current: Self {\n var systemInfo = utsname()\n uname(&systemInfo)\n let arch = withUnsafePointer(to: &systemInfo.machine) {\n $0.withMemoryRebound(to: CChar.self, capacity: 1) {\n String(cString: $0)\n }\n }\n switch arch {\n case \"arm64\":\n return .init(arch: \"arm64\", os: \"linux\", variant: \"v8\")\n case \"x86_64\":\n return .init(arch: \"amd64\", os: \"linux\")\n default:\n fatalError(\"unsupported arch \\(arch)\")\n }\n }\n\n /// The computed description, for example, `linux/arm64/v8`.\n public var description: String {\n let architecture = architecture\n if let variant = variant {\n return \"\\(os)/\\(architecture)/\\(variant)\"\n }\n return \"\\(os)/\\(architecture)\"\n }\n\n /// The CPU architecture, for example, `amd64` or `ppc64`.\n public var architecture: String {\n switch _rawArch {\n case \"arm64\", \"arm\", \"aarch64\", \"armhf\", \"armel\":\n return \"arm64\"\n case \"x86_64\", \"x86-64\", \"amd64\":\n return \"amd64\"\n case \"386\", \"ppc64le\", \"i386\", \"s390x\", \"riscv64\":\n return _rawArch\n default:\n return _rawArch\n }\n }\n\n /// The operating system, for example, `linux` or `windows`.\n public var os: String {\n _rawOS\n }\n\n /// An optional field specifying the operating system version, for example on Windows `10.0.14393.1066`.\n public var osVersion: String?\n\n /// An optional field specifying an array of strings, each listing a required OS feature (for example on Windows `win32k`).\n public var osFeatures: [String]?\n\n /// An optional field specifying a variant of the CPU, for example `v7` to specify ARMv7 when architecture is `arm`.\n public var variant: String?\n\n /// The operation system of the image (eg. `linux`).\n private let _rawOS: String\n /// The CPU architecture (eg. `arm64`).\n private let _rawArch: String\n\n public init(arch: String, os: String, osVersion: String? = nil, osFeatures: [String]? = nil, variant: String? = nil) {\n self._rawArch = arch\n self._rawOS = os\n self.osVersion = osVersion\n self.osFeatures = osFeatures\n self.variant = variant\n }\n\n /// Initializes a new platform from a string.\n /// - Parameters:\n /// - platform: A `string` value representing the platform.\n /// ```swift\n /// // Create a new `ImagePlatform` from string.\n /// let platform = try Platform(from: \"linux/amd64\")\n /// ```\n /// ## Throws ##\n /// - Throws: `Error.missingOS` if input is empty\n /// - Throws: `Error.invalidOS` if os is not `linux`\n /// - Throws: `Error.missingArch` if only one `/` is present\n /// - Throws: `Error.invalidArch` if an unrecognized architecture is provided\n /// - Throws: `Error.invalidVariant` if a variant is provided, and it does not apply to the specified architecture\n public init(from platform: String) throws {\n let items = platform.split(separator: \"/\", maxSplits: 1)\n guard let osValue = items.first else {\n throw ContainerizationError(.invalidArgument, message: \"Missing OS in \\(platform)\")\n }\n switch osValue {\n case \"linux\":\n _rawOS = osValue.description\n case \"darwin\":\n _rawOS = osValue.description\n case \"windows\":\n _rawOS = osValue.description\n default:\n throw ContainerizationError(.invalidArgument, message: \"Unknown OS in \\(osValue)\")\n }\n guard items.count > 1 else {\n throw ContainerizationError(.invalidArgument, message: \"Missing architecture in \\(platform)\")\n }\n\n guard let archItems = items.last?.split(separator: \"/\", maxSplits: 1, omittingEmptySubsequences: false) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing architecture in \\(platform)\")\n }\n\n guard let archName = archItems.first else {\n throw ContainerizationError(.invalidArgument, message: \"Missing architecture in \\(platform)\")\n }\n\n switch archName {\n case \"arm\", \"armhf\", \"armel\":\n _rawArch = \"arm\"\n variant = \"v7\"\n case \"aarch64\", \"arm64\":\n variant = \"v8\"\n _rawArch = \"arm64\"\n case \"x86_64\", \"x86-64\", \"amd64\":\n _rawArch = \"amd64\"\n default:\n _rawArch = archName.description\n }\n\n if archItems.count == 2 {\n guard let archVariant = archItems.last else {\n throw ContainerizationError(.invalidArgument, message: \"Missing variant in \\(platform)\")\n }\n\n switch archName {\n case \"arm\":\n switch archVariant {\n case \"v5\", \"v6\", \"v7\", \"v8\":\n variant = archVariant.description\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n case \"armhf\":\n switch archVariant {\n case \"v7\":\n variant = \"v7\"\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n case \"armel\":\n switch archVariant {\n case \"v6\":\n variant = \"v6\"\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n case \"aarch64\", \"arm64\":\n switch archVariant {\n case \"v8\", \"8\":\n variant = \"v8\"\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n case \"x86_64\", \"x86-64\", \"amd64\":\n switch archVariant {\n case \"v1\":\n variant = nil\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n case \"i386\", \"386\", \"ppc64le\", \"riscv64\":\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n default:\n throw ContainerizationError(.invalidArgument, message: \"Invalid variant \\(archVariant)\")\n }\n }\n }\n\n}\n\nextension Platform: Hashable {\n /**\n `~=` compares two platforms to check if **lhs** platform images are compatible with **rhs** platform\n This operator can be used to check if an image of **lhs** platform can run on **rhs**:\n - `true`: when **rhs**=`arm/v8`, **lhs** is any of `arm/v8`, `arm/v7`, `arm/v6` and `arm/v5`\n - `true`: when **rhs**=`arm/v7`, **lhs** is any of `arm/v7`, `arm/v6` and `arm/v5`\n - `true`: when **rhs**=`arm/v6`, **lhs** is any of `arm/v6` and `arm/v5`\n - `true`: when **rhs**=`amd64`, **lhs** is any of `amd64` and `386`\n - `true`: when **rhs**=**lhs**\n - `false`: otherwise\n - Parameters:\n - lhs: platform whose compatibility is being checked\n - rhs: platform against which compatibility is being checked\n - Returns: `true | false`\n */\n public static func ~= (lhs: Platform, rhs: Platform) -> Bool {\n if lhs.os == rhs.os {\n if lhs._rawArch == rhs._rawArch {\n switch rhs._rawArch {\n case \"arm\":\n guard let lVariant = lhs.variant else {\n return lhs == rhs\n }\n guard let rVariant = rhs.variant else {\n return lhs == rhs\n }\n switch rVariant {\n case \"v8\":\n switch lVariant {\n case \"v5\", \"v6\", \"v7\", \"v8\":\n return true\n default:\n return false\n }\n case \"v7\":\n switch lVariant {\n case \"v5\", \"v6\", \"v7\":\n return true\n default:\n return false\n }\n case \"v6\":\n switch lVariant {\n case \"v5\", \"v6\":\n return true\n default:\n return false\n }\n default:\n return lhs == rhs\n }\n default:\n return lhs == rhs\n }\n }\n if lhs._rawArch == \"386\" && rhs._rawArch == \"amd64\" {\n return true\n }\n }\n return false\n }\n\n /// `==` compares if **lhs** and **rhs** are the exact same platforms.\n public static func == (lhs: Platform, rhs: Platform) -> Bool {\n // NOTE:\n // If the platform struct was created by setting the fields directly and not using (from: String)\n // then, there is a possibility that for arm64 architecture, the variant may be set to nil\n // In that case, the variant should be assumed to v8\n if lhs.architecture == \"arm64\" && rhs.architecture == \"arm64\" {\n // The following checks effectively verify\n // that one operand has nil value and other has \"v8\"\n if lhs.variant == nil || rhs.variant == nil {\n if lhs.variant == \"v8\" || rhs.variant == \"v8\" {\n return true\n }\n }\n }\n\n let osEqual = lhs.os == rhs.os\n let archEqual = lhs.architecture == rhs.architecture\n let variantEqual = lhs.variant == rhs.variant\n\n return osEqual && archEqual && variantEqual\n }\n\n public func hash(into hasher: inout Swift.Hasher) {\n hasher.combine(description)\n }\n}\n\nextension Platform: Codable {\n\n enum CodingKeys: String, CodingKey {\n case os = \"os\"\n case architecture = \"architecture\"\n case variant = \"variant\"\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n try container.encode(os, forKey: .os)\n try container.encode(architecture, forKey: .architecture)\n try container.encodeIfPresent(variant, forKey: .variant)\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n let architecture = try container.decodeIfPresent(String.self, forKey: .architecture)\n guard let architecture else {\n throw ContainerizationError(.invalidArgument, message: \"Missing architecture\")\n }\n let os = try container.decodeIfPresent(String.self, forKey: .os)\n guard let os else {\n throw ContainerizationError(.invalidArgument, message: \"Missing OS\")\n }\n let variant = try container.decodeIfPresent(String.self, forKey: .variant)\n self.init(arch: architecture, os: os, variant: variant)\n }\n}\n\npublic func createPlatformMatcher(for platform: Platform?) -> @Sendable (Platform) -> Bool {\n if let platform {\n return { other in\n platform == other\n }\n }\n return { _ in\n true\n }\n}\n\npublic func filterPlatforms(matcher: (Platform) -> Bool, _ descriptors: [Descriptor]) throws -> [Descriptor] {\n var outDescriptors: [Descriptor] = []\n for desc in descriptors {\n guard let p = desc.platform else {\n // pass along descriptor if the platform is not defined\n outDescriptors.append(desc)\n continue\n }\n if matcher(p) {\n outDescriptors.append(desc)\n }\n }\n return outDescriptors\n}\n"], ["/containerization/Sources/ContainerizationArchive/Reader.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CArchive\nimport Foundation\n\n/// A class responsible for reading entries from an archive file.\npublic final class ArchiveReader {\n /// A pointer to the underlying `archive` C structure.\n var underlying: OpaquePointer?\n /// The file handle associated with the archive file being read.\n let fileHandle: FileHandle?\n\n /// Initializes an `ArchiveReader` to read from a specified file URL with an explicit `Format` and `Filter`.\n /// Note: This method must be used when it is known that the archive at the specified URL follows the specified\n /// `Format` and `Filter`.\n public convenience init(format: Format, filter: Filter, file: URL) throws {\n let fileHandle = try FileHandle(forReadingFrom: file)\n try self.init(format: format, filter: filter, fileHandle: fileHandle)\n }\n\n /// Initializes an `ArchiveReader` to read from the provided file descriptor with an explicit `Format` and `Filter`.\n /// Note: This method must be used when it is known that the archive pointed to by the file descriptor follows the specified\n /// `Format` and `Filter`.\n public init(format: Format, filter: Filter, fileHandle: FileHandle) throws {\n self.underlying = archive_read_new()\n self.fileHandle = fileHandle\n\n try archive_read_set_format(underlying, format.code)\n .checkOk(elseThrow: .unableToSetFormat(format.code, format))\n try archive_read_append_filter(underlying, filter.code)\n .checkOk(elseThrow: .unableToAddFilter(filter.code, filter))\n\n let fd = fileHandle.fileDescriptor\n try archive_read_open_fd(underlying, fd, 4096)\n .checkOk(elseThrow: { .unableToOpenArchive($0) })\n }\n\n /// Initialize the `ArchiveReader` to read from a specified file URL\n /// by trying to auto determine the archives `Format` and `Filter`.\n public init(file: URL) throws {\n self.underlying = archive_read_new()\n let fileHandle = try FileHandle(forReadingFrom: file)\n self.fileHandle = fileHandle\n try archive_read_support_filter_all(underlying)\n .checkOk(elseThrow: .failedToDetectFilter)\n try archive_read_support_format_all(underlying)\n .checkOk(elseThrow: .failedToDetectFormat)\n let fd = fileHandle.fileDescriptor\n try archive_read_open_fd(underlying, fd, 4096)\n .checkOk(elseThrow: { .unableToOpenArchive($0) })\n }\n\n deinit {\n archive_read_free(underlying)\n try? fileHandle?.close()\n }\n}\n\nextension CInt {\n fileprivate func checkOk(elseThrow error: @autoclosure () -> ArchiveError) throws {\n guard self == ARCHIVE_OK else { throw error() }\n }\n fileprivate func checkOk(elseThrow error: (CInt) -> ArchiveError) throws {\n guard self == ARCHIVE_OK else { throw error(self) }\n }\n\n}\n\nextension ArchiveReader: Sequence {\n public func makeIterator() -> Iterator {\n Iterator(reader: self)\n }\n\n public struct Iterator: IteratorProtocol {\n var reader: ArchiveReader\n\n public mutating func next() -> (WriteEntry, Data)? {\n let entry = WriteEntry()\n let result = archive_read_next_header2(reader.underlying, entry.underlying)\n if result == ARCHIVE_EOF {\n return nil\n }\n let data = reader.readDataForEntry(entry)\n return (entry, data)\n }\n }\n\n internal func readDataForEntry(_ entry: WriteEntry) -> Data {\n let bufferSize = Int(Swift.min(entry.size ?? 4096, 4096))\n var entry = Data()\n var part = Data(count: bufferSize)\n while true {\n let c = part.withUnsafeMutableBytes { buffer in\n guard let baseAddress = buffer.baseAddress else {\n return 0\n }\n return archive_read_data(self.underlying, baseAddress, buffer.count)\n }\n guard c > 0 else { break }\n part.count = c\n entry.append(part)\n }\n return entry\n }\n}\n\nextension ArchiveReader {\n public convenience init(name: String, bundle: Data, tempDirectoryBaseName: String? = nil) throws {\n let baseName = tempDirectoryBaseName ?? \"Unarchiver\"\n let url = createTemporaryDirectory(baseName: baseName)!.appendingPathComponent(name)\n try bundle.write(to: url, options: .atomic)\n try self.init(format: .zip, filter: .none, file: url)\n }\n\n /// Extracts the contents of an archive to the provided directory.\n /// Currently only handles regular files and directories present in the archive.\n public func extractContents(to directory: URL) throws {\n let fm = FileManager.default\n var foundEntry = false\n for (entry, data) in self {\n guard let p = entry.path else { continue }\n foundEntry = true\n let type = entry.fileType\n let target = directory.appending(path: p)\n switch type {\n case .regular:\n try data.write(to: target, options: .atomic)\n case .directory:\n try fm.createDirectory(at: target, withIntermediateDirectories: true)\n case .symbolicLink:\n guard let symlinkTarget = entry.symlinkTarget, let linkTargetURL = URL(string: symlinkTarget, relativeTo: target) else {\n continue\n }\n try fm.createSymbolicLink(at: target, withDestinationURL: linkTargetURL)\n default:\n continue\n }\n chmod(target.path(), entry.permissions)\n if let owner = entry.owner, let group = entry.group {\n chown(target.path(), owner, group)\n }\n }\n guard foundEntry else {\n throw ArchiveError.failedToExtractArchive(\"No entries found in archive\")\n }\n }\n\n /// This method extracts a given file from the archive.\n /// This operation modifies the underlying file descriptor's position within the archive,\n /// meaning subsequent reads will start from a new location.\n /// To reset the underlying file descriptor to the beginning of the archive, close and\n /// reopen the archive.\n public func extractFile(path: String) throws -> (WriteEntry, Data) {\n let entry = WriteEntry()\n while archive_read_next_header2(self.underlying, entry.underlying) != ARCHIVE_EOF {\n guard let entryPath = entry.path else { continue }\n let trimCharSet = CharacterSet(charactersIn: \"./\")\n let trimmedEntry = entryPath.trimmingCharacters(in: trimCharSet)\n let trimmedRequired = path.trimmingCharacters(in: trimCharSet)\n guard trimmedEntry == trimmedRequired else { continue }\n let data = readDataForEntry(entry)\n return (entry, data)\n }\n throw ArchiveError.failedToExtractArchive(\" \\(path) not found in archive\")\n }\n}\n"], ["/containerization/Sources/Integration/Suite.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport NIOCore\n\nlet log = {\n LoggingSystem.bootstrap(StreamLogHandler.standardError)\n var log = Logger(label: \"com.apple.containerization\")\n log.logLevel = .debug\n return log\n}()\n\nenum IntegrationError: Swift.Error {\n case assert(msg: String)\n case noOutput\n}\n\nstruct SkipTest: Swift.Error, CustomStringConvertible {\n let reason: String\n\n var description: String {\n reason\n }\n}\n\n@main\nstruct IntegrationSuite: AsyncParsableCommand {\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.containerization\")\n }()\n\n private static let _contentStore: ContentStore = {\n try! LocalContentStore(path: appRoot.appending(path: \"content\"))\n }()\n\n private static let _imageStore: ImageStore = {\n try! ImageStore(\n path: appRoot,\n contentStore: contentStore\n )\n }()\n\n static let _testDir: URL = {\n FileManager.default.uniqueTemporaryDirectory(create: true)\n }()\n\n static var testDir: URL {\n _testDir\n }\n\n static var imageStore: ImageStore {\n _imageStore\n }\n\n static var contentStore: ContentStore {\n _contentStore\n }\n\n static let initImage = \"vminit:latest\"\n\n @Option(name: .shortAndLong, help: \"Path to a log file\")\n var bootlog: String\n\n @Option(name: .shortAndLong, help: \"Path to a kernel binary\")\n var kernel: String = \"./bin/vmlinux\"\n\n static func binPath(name: String) -> URL {\n URL(fileURLWithPath: FileManager.default.currentDirectoryPath)\n .appendingPathComponent(\"bin\")\n .appendingPathComponent(name)\n }\n\n func bootstrap() async throws -> (rootfs: Containerization.Mount, vmm: VirtualMachineManager, image: Containerization.Image) {\n let reference = \"ghcr.io/linuxcontainers/alpine:3.20\"\n let store = Self.imageStore\n\n let initImage = try await store.getInitImage(reference: Self.initImage)\n let initfs = try await {\n let p = Self.binPath(name: \"init.block\")\n do {\n return try await initImage.initBlock(at: p, for: .linuxArm)\n } catch let err as ContainerizationError {\n guard err.code == .exists else {\n throw err\n }\n return .block(\n format: \"ext4\",\n source: p.absolutePath(),\n destination: \"/\",\n options: [\"ro\"]\n )\n }\n }()\n\n var testKernel = Kernel(path: .init(filePath: kernel), platform: .linuxArm)\n testKernel.commandLine.addDebug()\n let image = try await Self.fetchImage(reference: reference, store: store)\n let platform = Platform(arch: \"arm64\", os: \"linux\", variant: \"v8\")\n\n let fs: Containerization.Mount = try await {\n let fsPath = Self.testDir.appending(component: \"rootfs.ext4\")\n do {\n let unpacker = EXT4Unpacker(blockSizeInBytes: 2.gib())\n return try await unpacker.unpack(image, for: platform, at: fsPath)\n } catch let err as ContainerizationError {\n if err.code == .exists {\n return .block(\n format: \"ext4\",\n source: fsPath.absolutePath(),\n destination: \"/\",\n options: []\n )\n }\n throw err\n }\n }()\n\n let clPath = Self.testDir.appending(component: \"rn.ext4\").absolutePath()\n try? FileManager.default.removeItem(atPath: clPath)\n\n let cl = try fs.clone(to: clPath)\n return (\n cl,\n VZVirtualMachineManager(\n kernel: testKernel,\n initialFilesystem: initfs,\n bootlog: bootlog\n ),\n image\n )\n }\n\n static func fetchImage(reference: String, store: ImageStore) async throws -> Containerization.Image {\n do {\n return try await store.get(reference: reference)\n } catch let error as ContainerizationError {\n if error.code == .notFound {\n return try await store.pull(reference: reference)\n }\n throw error\n }\n }\n\n static func adjustLimits() throws {\n var limits = rlimit()\n guard getrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n limits.rlim_cur = 65536\n limits.rlim_max = 65536\n\n guard setrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n }\n\n // Why does this exist?\n //\n // We need the virtualization entitlement to execute these tests.\n // There currently does not exist a straightforward way to do this\n // in a pure swift package.\n //\n // In order to not have a dependency on xcode, we create an executable\n // for our integration tests that can be signed then ran.\n //\n // We also can't import Testing as it expects to be run from a runner.\n // Hopefully this improves over time.\n func run() async throws {\n try Self.adjustLimits()\n let suiteStarted = CFAbsoluteTimeGetCurrent()\n log.info(\"starting integration suite\\n\")\n\n let tests: [String: () async throws -> Void] = [\n \"process true\": testProcessTrue,\n \"process false\": testProcessFalse,\n \"process echo hi\": testProcessEchoHi,\n \"process user\": testProcessUser,\n \"process stdin\": testProcessStdin,\n \"process home envvar\": testProcessHomeEnvvar,\n \"process custom home envvar\": testProcessCustomHomeEnvvar,\n \"process tty ensure TERM\": testProcessTtyEnvvar,\n \"multiple concurrent processes\": testMultipleConcurrentProcesses,\n \"multiple concurrent processes with output stress\": testMultipleConcurrentProcessesOutputStress,\n \"container hostname\": testHostname,\n \"container hosts\": testHostsFile,\n \"container mount\": testMounts,\n \"nested virt\": testNestedVirtualizationEnabled,\n \"container manager\": testContainerManagerCreate,\n ]\n\n var passed = 0\n var skipped = 0\n for (name, test) in tests {\n do {\n log.info(\"test \\(name) started...\")\n\n let started = CFAbsoluteTimeGetCurrent()\n try await test()\n let lasted = CFAbsoluteTimeGetCurrent() - started\n log.info(\"✅ test \\(name) complete in \\(lasted)s.\")\n passed += 1\n } catch let err as SkipTest {\n log.info(\"⏭️ skipped test: \\(err)\")\n skipped += 1\n } catch {\n log.error(\"❌ test \\(name) failed: \\(error)\")\n }\n }\n\n let ended = CFAbsoluteTimeGetCurrent() - suiteStarted\n var finishingText = \"\\n\\nIntegration suite completed in \\(ended)s with \\(passed)/\\(tests.count) passed\"\n if skipped > 0 {\n finishingText += \" and \\(skipped)/\\(tests.count) skipped\"\n }\n finishingText += \"!\"\n\n log.info(\"\\(finishingText)\")\n\n if passed + skipped < tests.count {\n log.error(\"❌\")\n throw ExitCode(1)\n }\n try? FileManager.default.removeItem(at: Self.testDir)\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Socket/UnixType.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if canImport(Musl)\nimport Musl\nlet _SOCK_STREAM = SOCK_STREAM\n#elseif canImport(Glibc)\nimport Glibc\nlet _SOCK_STREAM = Int32(SOCK_STREAM.rawValue)\n#elseif canImport(Darwin)\nimport Darwin\nlet _SOCK_STREAM = SOCK_STREAM\n#else\n#error(\"UnixType not supported on this platform.\")\n#endif\n\n/// Unix domain socket variant of `SocketType`.\npublic struct UnixType: SocketType, Sendable, CustomStringConvertible {\n public var domain: Int32 { AF_UNIX }\n public var type: Int32 { _SOCK_STREAM }\n public var description: String {\n path\n }\n\n public let path: String\n public let perms: mode_t?\n private let _addr: sockaddr_un\n private let _unlinkExisting: Bool\n\n private init(sockaddr: sockaddr_un) {\n let pathname: String = withUnsafePointer(to: sockaddr.sun_path) { ptr in\n let charPtr = UnsafeRawPointer(ptr).assumingMemoryBound(to: CChar.self)\n return String(cString: charPtr)\n }\n self._addr = sockaddr\n self.path = pathname\n self._unlinkExisting = false\n self.perms = nil\n }\n\n /// Mode and unlinkExisting only used if the socket is going to be a listening socket.\n public init(\n path: String,\n perms: mode_t? = nil,\n unlinkExisting: Bool = false\n ) throws {\n self.path = path\n self.perms = perms\n self._unlinkExisting = unlinkExisting\n var addr = sockaddr_un()\n addr.sun_family = sa_family_t(AF_UNIX)\n\n let socketName = path\n let nameLength = socketName.utf8.count\n\n #if os(macOS)\n // Funnily enough, this isn't limited by sun path on macOS even though\n // it's stated as so.\n let lengthLimit = 253\n #elseif os(Linux)\n let lengthLimit = MemoryLayout.size(ofValue: addr.sun_path)\n #endif\n\n guard nameLength < lengthLimit else {\n throw Error.nameTooLong(path)\n }\n\n _ = withUnsafeMutablePointer(to: &addr.sun_path.0) { ptr in\n socketName.withCString { strncpy(ptr, $0, nameLength) }\n }\n\n #if os(macOS)\n addr.sun_len = UInt8(MemoryLayout.size + MemoryLayout.size + socketName.utf8.count + 1)\n #endif\n self._addr = addr\n }\n\n public func accept(fd: Int32) throws -> (Int32, SocketType) {\n var clientFD: Int32 = -1\n var addr = sockaddr_un()\n\n clientFD = Syscall.retrying {\n var size = socklen_t(MemoryLayout.stride)\n return withUnsafeMutablePointer(to: &addr) { pointer in\n pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { pointer in\n sysAccept(fd, pointer, &size)\n }\n }\n }\n if clientFD < 0 {\n throw Socket.errnoToError(msg: \"accept failed\")\n }\n\n return (clientFD, UnixType(sockaddr: addr))\n }\n\n public func beforeBind(fd: Int32) throws {\n #if os(Linux)\n // Only Linux supports setting the mode of a socket before binding.\n if let perms = self.perms {\n guard fchmod(fd, perms) == 0 else {\n throw Socket.errnoToError(msg: \"fchmod failed\")\n }\n }\n #endif\n\n var rc: Int32 = 0\n if self._unlinkExisting {\n rc = sysUnlink(self.path)\n if rc != 0 && errno != ENOENT {\n throw Socket.errnoToError(msg: \"failed to remove old socket at \\(self.path)\")\n }\n }\n }\n\n public func beforeListen(fd: Int32) throws {\n #if os(macOS)\n if let perms = self.perms {\n guard chmod(self.path, perms) == 0 else {\n throw Socket.errnoToError(msg: \"chmod failed\")\n }\n }\n #endif\n }\n\n public func withSockAddr(_ closure: (UnsafePointer, UInt32) throws -> Void) throws {\n var addr = self._addr\n try withUnsafePointer(to: &addr) {\n let addrBytes = UnsafeRawPointer($0).assumingMemoryBound(to: sockaddr.self)\n try closure(addrBytes, UInt32(MemoryLayout.stride))\n }\n }\n}\n\nextension UnixType {\n /// `UnixType` errors.\n public enum Error: Swift.Error, CustomStringConvertible {\n case nameTooLong(_: String)\n\n public var description: String {\n switch self {\n case .nameTooLong(let name):\n return \"\\(name) is too long for a Unix Domain Socket path\"\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/UInt8+DataBinding.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension ArraySlice {\n package func hexEncodedString() -> String {\n self.map { String(format: \"%02hhx\", $0) }.joined()\n }\n}\n\nextension [UInt8] {\n package func hexEncodedString() -> String {\n self.map { String(format: \"%02hhx\", $0) }.joined()\n }\n\n package mutating func bind(as type: T.Type, offset: Int = 0, size: Int? = nil) -> UnsafeMutablePointer? {\n guard self.count >= (size ?? MemoryLayout.size) + offset else {\n return nil\n }\n\n return self.withUnsafeMutableBytes { $0.baseAddress?.advanced(by: offset).assumingMemoryBound(to: T.self) }\n }\n\n package mutating func copyIn(as type: T.Type, value: T, offset: Int = 0, size: Int? = nil) -> Int? {\n let size = size ?? MemoryLayout.size\n guard self.count >= size - offset else {\n return nil\n }\n\n return self.withUnsafeMutableBytes {\n $0.baseAddress?.advanced(by: offset).assumingMemoryBound(to: T.self).pointee = value\n return offset + MemoryLayout.size\n }\n }\n\n package mutating func copyOut(as type: T.Type, offset: Int = 0, size: Int? = nil) -> (Int, T)? {\n guard self.count >= (size ?? MemoryLayout.size) - offset else {\n return nil\n }\n\n return self.withUnsafeMutableBytes {\n guard let value = $0.baseAddress?.advanced(by: offset).assumingMemoryBound(to: T.self).pointee else {\n return nil\n }\n return (offset + MemoryLayout.size, value)\n }\n }\n\n package mutating func copyIn(buffer: [UInt8], offset: Int = 0) -> Int? {\n guard offset + buffer.count <= self.count else {\n return nil\n }\n\n self[offset.. Int? {\n guard offset + buffer.count <= self.count else {\n return nil\n }\n\n buffer[0.. Descriptor {\n var components = base\n\n // Make HEAD request to retrieve the digest header\n components.path = \"/v2/\\(name)/manifests/\\(tag)\"\n\n // The client should include an Accept header indicating which manifest content types it supports.\n let mediaTypes = [\n MediaTypes.dockerManifest,\n MediaTypes.dockerManifestList,\n MediaTypes.imageManifest,\n MediaTypes.index,\n \"*/*\",\n ]\n\n let headers = [\n (\"Accept\", mediaTypes.joined(separator: \", \"))\n ]\n\n return try await request(components: components, method: .HEAD, headers: headers) { response in\n guard response.status == .ok else {\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n\n guard let digest = response.headers.first(name: \"Docker-Content-Digest\") else {\n throw ContainerizationError(.invalidArgument, message: \"Missing required header Docker-Content-Digest\")\n }\n\n guard let type = response.headers.first(name: \"Content-Type\") else {\n throw ContainerizationError(.invalidArgument, message: \"Missing required header Content-Type\")\n }\n\n guard let sizeStr = response.headers.first(name: \"Content-Length\") else {\n throw ContainerizationError(.invalidArgument, message: \"Missing required header Content-Length\")\n }\n\n guard let size = Int64(sizeStr) else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot convert \\(sizeStr) to Int64\")\n }\n\n return Descriptor(mediaType: type, digest: digest, size: size)\n }\n }\n\n /// Fetch resource (either manifest or blob) to memory with JSON decoding.\n public func fetch(name: String, descriptor: Descriptor) async throws -> T {\n var components = base\n\n let manifestTypes = [\n MediaTypes.dockerManifest,\n MediaTypes.dockerManifestList,\n MediaTypes.imageManifest,\n MediaTypes.index,\n ]\n\n let isManifest = manifestTypes.contains(where: { $0 == descriptor.mediaType })\n let resource = isManifest ? \"manifests\" : \"blobs\"\n\n components.path = \"/v2/\\(name)/\\(resource)/\\(descriptor.digest)\"\n\n let mediaType = descriptor.mediaType\n if mediaType.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Missing media type for descriptor \\(descriptor.digest)\")\n }\n\n let headers = [\n (\"Accept\", mediaType)\n ]\n\n return try await requestJSON(components: components, headers: headers)\n }\n\n /// Fetch resource (either manifest or blob) to memory as raw `Data`.\n public func fetchData(name: String, descriptor: Descriptor) async throws -> Data {\n var components = base\n\n let manifestTypes = [\n MediaTypes.dockerManifest,\n MediaTypes.dockerManifestList,\n MediaTypes.imageManifest,\n MediaTypes.index,\n ]\n\n let isManifest = manifestTypes.contains(where: { $0 == descriptor.mediaType })\n let resource = isManifest ? \"manifests\" : \"blobs\"\n\n components.path = \"/v2/\\(name)/\\(resource)/\\(descriptor.digest)\"\n\n let mediaType = descriptor.mediaType\n if mediaType.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Missing media type for descriptor \\(descriptor.digest)\")\n }\n\n let headers = [\n (\"Accept\", mediaType)\n ]\n\n return try await requestData(components: components, headers: headers)\n }\n\n /// Fetch a blob from remote registry.\n /// This method is suitable for streaming data.\n public func fetchBlob(\n name: String,\n descriptor: Descriptor,\n closure: (Int64, HTTPClientResponse.Body) async throws -> Void\n ) async throws {\n var components = base\n components.path = \"/v2/\\(name)/blobs/\\(descriptor.digest)\"\n\n let mediaType = descriptor.mediaType\n if mediaType.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Missing media type for descriptor \\(descriptor.digest)\")\n }\n\n let headers = [\n (\"Accept\", mediaType)\n ]\n\n try await request(components: components, headers: headers) { response in\n guard response.status == .ok else {\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n\n // How many bytes to expect\n guard let expectedBytes = response.headers.first(name: \"Content-Length\").flatMap(Int64.init) else {\n throw ContainerizationError(.invalidArgument, message: \"Missing required header Content-Length\")\n }\n\n try await closure(expectedBytes, response.body)\n }\n }\n\n #if os(macOS)\n /// Fetch a blob from remote registry and write the contents into a file in the provided directory.\n public func fetchBlob(name: String, descriptor: Descriptor, into file: URL, progress: ProgressHandler?) async throws -> (Int64, SHA256Digest) {\n var hasher = SHA256()\n var received: Int64 = 0\n let fs = NIOFileSystem.FileSystem.shared\n let handle = try await fs.openFile(forWritingAt: FilePath(file.absolutePath()), options: .newFile(replaceExisting: true))\n var writer = handle.bufferedWriter()\n do {\n try await self.fetchBlob(name: name, descriptor: descriptor) { (size, body) in\n var itr = body.makeAsyncIterator()\n while let buf = try await itr.next() {\n let readBytes = Int64(buf.readableBytes)\n received += readBytes\n let written = try await writer.write(contentsOf: buf)\n await progress?([\n ProgressEvent(event: \"add-size\", value: written)\n ])\n guard written == readBytes else {\n throw ContainerizationError(\n .internalError,\n message: \"Could not write \\(readBytes) bytes to file \\(file)\"\n )\n }\n hasher.update(data: buf.readableBytesView)\n }\n }\n try await writer.flush()\n try await handle.close()\n } catch {\n try? await handle.close()\n throw error\n }\n let computedDigest = hasher.finalize()\n return (received, computedDigest)\n }\n #else\n /// Fetch a blob from remote registry and write the contents into a file in the provided directory.\n public func fetchBlob(name: String, descriptor: Descriptor, into file: URL, progress: ProgressHandler?) async throws -> (Int64, SHA256Digest) {\n var hasher = SHA256()\n var received: Int64 = 0\n guard FileManager.default.createFile(atPath: file.path, contents: nil) else {\n throw ContainerizationError(.internalError, message: \"Cannot create file at path \\(file.path)\")\n }\n try await self.fetchBlob(name: name, descriptor: descriptor) { (size, body) in\n let fd = try FileHandle(forWritingTo: file)\n defer {\n try? fd.close()\n }\n var itr = body.makeAsyncIterator()\n while let buf = try await itr.next() {\n let readBytes = Int64(buf.readableBytes)\n received += readBytes\n await progress?([\n ProgressEvent(event: \"add-size\", value: readBytes)\n ])\n try fd.write(contentsOf: buf.readableBytesView)\n hasher.update(data: buf.readableBytesView)\n }\n }\n let computedDigest = hasher.finalize()\n return (received, computedDigest)\n }\n #endif\n}\n"], ["/containerization/Sources/ContainerizationOCI/Spec.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// NOTE: This is not a complete recreation of the runtime spec. Other platforms outside of Linux\n/// have been left off, and some APIs for Linux aren't present. This was manually ported starting\n/// at the v1.2.0 release.\n\npublic struct Spec: Codable, Sendable {\n public var version: String\n public var hooks: Hook?\n public var process: Process?\n public var hostname, domainname: String\n public var mounts: [Mount]\n public var annotations: [String: String]?\n public var root: Root?\n public var linux: Linux?\n\n public init(\n version: String = \"\",\n hooks: Hook? = nil,\n process: Process? = nil,\n hostname: String = \"\",\n domainname: String = \"\",\n mounts: [Mount] = [],\n annotations: [String: String]? = nil,\n root: Root? = nil,\n linux: Linux? = nil\n ) {\n self.version = version\n self.hooks = hooks\n self.process = process\n self.hostname = hostname\n self.domainname = domainname\n self.mounts = mounts\n self.annotations = annotations\n self.root = root\n self.linux = linux\n }\n\n public enum CodingKeys: String, CodingKey {\n case version = \"ociVersion\"\n case hooks\n case process\n case hostname\n case domainname\n case mounts\n case annotations\n case root\n case linux\n }\n}\n\npublic struct Process: Codable, Sendable {\n public var cwd: String\n public var env: [String]\n public var consoleSize: Box?\n public var selinuxLabel: String\n public var noNewPrivileges: Bool\n public var commandLine: String\n public var oomScoreAdj: Int?\n public var capabilities: LinuxCapabilities?\n public var apparmorProfile: String\n public var user: User\n public var rlimits: [POSIXRlimit]\n public var args: [String]\n public var terminal: Bool\n\n public init(\n args: [String] = [],\n cwd: String = \"/\",\n env: [String] = [],\n consoleSize: Box? = nil,\n selinuxLabel: String = \"\",\n noNewPrivileges: Bool = false,\n commandLine: String = \"\",\n oomScoreAdj: Int? = nil,\n capabilities: LinuxCapabilities? = nil,\n apparmorProfile: String = \"\",\n user: User = .init(),\n rlimits: [POSIXRlimit] = [],\n terminal: Bool = false\n ) {\n self.cwd = cwd\n self.env = env\n self.consoleSize = consoleSize\n self.selinuxLabel = selinuxLabel\n self.noNewPrivileges = noNewPrivileges\n self.commandLine = commandLine\n self.oomScoreAdj = oomScoreAdj\n self.capabilities = capabilities\n self.apparmorProfile = apparmorProfile\n self.user = user\n self.rlimits = rlimits\n self.args = args\n self.terminal = terminal\n }\n\n public init(from config: ImageConfig) {\n let cwd = config.workingDir ?? \"/\"\n let env = config.env ?? []\n let args = (config.entrypoint ?? []) + (config.cmd ?? [])\n let user: User = {\n if let rawString = config.user {\n return User(username: rawString)\n }\n return User()\n }()\n self.init(args: args, cwd: cwd, env: env, user: user)\n }\n}\n\npublic struct LinuxCapabilities: Codable, Sendable {\n public var bounding: [String]\n public var effective: [String]\n public var inheritable: [String]\n public var permitted: [String]\n public var ambient: [String]\n\n public init(\n bounding: [String],\n effective: [String],\n inheritable: [String],\n permitted: [String],\n ambient: [String]\n ) {\n self.bounding = bounding\n self.effective = effective\n self.inheritable = inheritable\n self.permitted = permitted\n self.ambient = ambient\n }\n}\n\npublic struct Box: Codable, Sendable {\n var height, width: UInt\n\n public init(height: UInt, width: UInt) {\n self.height = height\n self.width = width\n }\n}\n\npublic struct User: Codable, Sendable {\n public var uid: UInt32\n public var gid: UInt32\n public var umask: UInt32?\n public var additionalGids: [UInt32]\n public var username: String\n\n public init(\n uid: UInt32 = 0,\n gid: UInt32 = 0,\n umask: UInt32? = nil,\n additionalGids: [UInt32] = [],\n username: String = \"\"\n ) {\n self.uid = uid\n self.gid = gid\n self.umask = umask\n self.additionalGids = additionalGids\n self.username = username\n }\n}\n\npublic struct Root: Codable, Sendable {\n public var path: String\n public var readonly: Bool\n\n public init(path: String, readonly: Bool) {\n self.path = path\n self.readonly = readonly\n }\n}\n\npublic struct Mount: Codable, Sendable {\n public var type: String\n public var source: String\n public var destination: String\n public var options: [String]\n\n public var uidMappings: [LinuxIDMapping]\n public var gidMappings: [LinuxIDMapping]\n\n public init(\n type: String,\n source: String,\n destination: String,\n options: [String] = [],\n uidMappings: [LinuxIDMapping] = [],\n gidMappings: [LinuxIDMapping] = []\n ) {\n self.destination = destination\n self.type = type\n self.source = source\n self.options = options\n self.uidMappings = uidMappings\n self.gidMappings = gidMappings\n }\n}\n\npublic struct Hook: Codable, Sendable {\n public var path: String\n public var args: [String]\n public var env: [String]\n public var timeout: Int?\n\n public init(path: String, args: [String], env: [String], timeout: Int?) {\n self.path = path\n self.args = args\n self.env = env\n self.timeout = timeout\n }\n}\n\npublic struct Hooks: Codable, Sendable {\n public var prestart: [Hook]\n public var createRuntime: [Hook]\n public var createContainer: [Hook]\n public var startContainer: [Hook]\n public var poststart: [Hook]\n public var poststop: [Hook]\n\n public init(\n prestart: [Hook],\n createRuntime: [Hook],\n createContainer: [Hook],\n startContainer: [Hook],\n poststart: [Hook],\n poststop: [Hook]\n ) {\n self.prestart = prestart\n self.createRuntime = createRuntime\n self.createContainer = createContainer\n self.startContainer = startContainer\n self.poststart = poststart\n self.poststop = poststop\n }\n}\n\npublic struct Linux: Codable, Sendable {\n public var uidMappings: [LinuxIDMapping]\n public var gidMappings: [LinuxIDMapping]\n public var sysctl: [String: String]?\n public var resources: LinuxResources?\n public var cgroupsPath: String\n public var namespaces: [LinuxNamespace]\n public var devices: [LinuxDevice]\n public var seccomp: LinuxSeccomp?\n public var rootfsPropagation: String\n public var maskedPaths: [String]\n public var readonlyPaths: [String]\n public var mountLabel: String\n public var personality: LinuxPersonality?\n\n public init(\n uidMappings: [LinuxIDMapping] = [],\n gidMappings: [LinuxIDMapping] = [],\n sysctl: [String: String]? = nil,\n resources: LinuxResources? = nil,\n cgroupsPath: String = \"\",\n namespaces: [LinuxNamespace] = [],\n devices: [LinuxDevice] = [],\n seccomp: LinuxSeccomp? = nil,\n rootfsPropagation: String = \"\",\n maskedPaths: [String] = [],\n readonlyPaths: [String] = [],\n mountLabel: String = \"\",\n personality: LinuxPersonality? = nil\n ) {\n self.uidMappings = uidMappings\n self.gidMappings = gidMappings\n self.sysctl = sysctl\n self.resources = resources\n self.cgroupsPath = cgroupsPath\n self.namespaces = namespaces\n self.devices = devices\n self.seccomp = seccomp\n self.rootfsPropagation = rootfsPropagation\n self.maskedPaths = maskedPaths\n self.readonlyPaths = readonlyPaths\n self.mountLabel = mountLabel\n self.personality = personality\n }\n}\n\npublic struct LinuxNamespace: Codable, Sendable {\n public var type: LinuxNamespaceType\n public var path: String\n\n public init(type: LinuxNamespaceType, path: String = \"\") {\n self.type = type\n self.path = path\n }\n}\n\npublic enum LinuxNamespaceType: String, Codable, Sendable {\n case pid\n case network\n case uts\n case mount\n case ipc\n case user\n case cgroup\n}\n\npublic struct LinuxIDMapping: Codable, Sendable {\n public var containerID: UInt32\n public var hostID: UInt32\n public var size: UInt32\n\n public init(containerID: UInt32, hostID: UInt32, size: UInt32) {\n self.containerID = containerID\n self.hostID = hostID\n self.size = size\n }\n}\n\npublic struct POSIXRlimit: Codable, Sendable {\n public var type: String\n public var hard: UInt64\n public var soft: UInt64\n\n public init(type: String, hard: UInt64, soft: UInt64) {\n self.type = type\n self.hard = hard\n self.soft = soft\n }\n}\n\npublic struct LinuxHugepageLimit: Codable, Sendable {\n public var pagesize: String\n public var limit: UInt64\n\n public init(pagesize: String, limit: UInt64) {\n self.pagesize = pagesize\n self.limit = limit\n }\n}\n\npublic struct LinuxInterfacePriority: Codable, Sendable {\n public var name: String\n public var priority: UInt32\n\n public init(name: String, priority: UInt32) {\n self.name = name\n self.priority = priority\n }\n}\n\npublic struct LinuxBlockIODevice: Codable, Sendable {\n public var major: Int64\n public var minor: Int64\n\n public init(major: Int64, minor: Int64) {\n self.major = major\n self.minor = minor\n }\n}\n\npublic struct LinuxWeightDevice: Codable, Sendable {\n public var major: Int64\n public var minor: Int64\n public var weight: UInt16?\n public var leafWeight: UInt16?\n\n public init(major: Int64, minor: Int64, weight: UInt16?, leafWeight: UInt16?) {\n self.major = major\n self.minor = minor\n self.weight = weight\n self.leafWeight = leafWeight\n }\n}\n\npublic struct LinuxThrottleDevice: Codable, Sendable {\n public var major: Int64\n public var minor: Int64\n public var rate: UInt64\n\n public init(major: Int64, minor: Int64, rate: UInt64) {\n self.major = major\n self.minor = minor\n self.rate = rate\n }\n}\n\npublic struct LinuxBlockIO: Codable, Sendable {\n public var weight: UInt16?\n public var leafWeight: UInt16?\n public var weightDevice: [LinuxWeightDevice]\n public var throttleReadBpsDevice: [LinuxThrottleDevice]\n public var throttleWriteBpsDevice: [LinuxThrottleDevice]\n public var throttleReadIOPSDevice: [LinuxThrottleDevice]\n public var throttleWriteIOPSDevice: [LinuxThrottleDevice]\n\n public init(\n weight: UInt16?,\n leafWeight: UInt16?,\n weightDevice: [LinuxWeightDevice],\n throttleReadBpsDevice: [LinuxThrottleDevice],\n throttleWriteBpsDevice: [LinuxThrottleDevice],\n throttleReadIOPSDevice: [LinuxThrottleDevice],\n throttleWriteIOPSDevice: [LinuxThrottleDevice]\n ) {\n self.weight = weight\n self.leafWeight = leafWeight\n self.weightDevice = weightDevice\n self.throttleReadBpsDevice = throttleReadBpsDevice\n self.throttleWriteBpsDevice = throttleWriteBpsDevice\n self.throttleReadIOPSDevice = throttleReadIOPSDevice\n self.throttleWriteIOPSDevice = throttleWriteIOPSDevice\n }\n}\n\npublic struct LinuxMemory: Codable, Sendable {\n public var limit: Int64?\n public var reservation: Int64?\n public var swap: Int64?\n public var kernel: Int64?\n public var kernelTCP: Int64?\n public var swappiness: UInt64?\n public var disableOOMKiller: Bool?\n public var useHierarchy: Bool?\n public var checkBeforeUpdate: Bool?\n\n public init(\n limit: Int64? = nil,\n reservation: Int64? = nil,\n swap: Int64? = nil,\n kernel: Int64? = nil,\n kernelTCP: Int64? = nil,\n swappiness: UInt64? = nil,\n disableOOMKiller: Bool? = nil,\n useHierarchy: Bool? = nil,\n checkBeforeUpdate: Bool? = nil\n ) {\n self.limit = limit\n self.reservation = reservation\n self.swap = swap\n self.kernel = kernel\n self.kernelTCP = kernelTCP\n self.swappiness = swappiness\n self.disableOOMKiller = disableOOMKiller\n self.useHierarchy = useHierarchy\n self.checkBeforeUpdate = checkBeforeUpdate\n }\n}\n\npublic struct LinuxCPU: Codable, Sendable {\n public var shares: UInt64?\n public var quota: Int64?\n public var burst: UInt64?\n public var period: UInt64?\n public var realtimeRuntime: Int64?\n public var realtimePeriod: Int64?\n public var cpus: String\n public var mems: String\n public var idle: Int64?\n\n public init(\n shares: UInt64?,\n quota: Int64?,\n burst: UInt64?,\n period: UInt64?,\n realtimeRuntime: Int64?,\n realtimePeriod: Int64?,\n cpus: String,\n mems: String,\n idle: Int64?\n ) {\n self.shares = shares\n self.quota = quota\n self.burst = burst\n self.period = period\n self.realtimeRuntime = realtimeRuntime\n self.realtimePeriod = realtimePeriod\n self.cpus = cpus\n self.mems = mems\n self.idle = idle\n }\n}\n\npublic struct LinuxPids: Codable, Sendable {\n public var limit: Int64\n\n public init(limit: Int64) {\n self.limit = limit\n }\n}\n\npublic struct LinuxNetwork: Codable, Sendable {\n public var classID: UInt32?\n public var priorities: [LinuxInterfacePriority]\n\n public init(classID: UInt32?, priorities: [LinuxInterfacePriority]) {\n self.classID = classID\n self.priorities = priorities\n }\n}\n\npublic struct LinuxRdma: Codable, Sendable {\n public var hcsHandles: UInt32?\n public var hcaObjects: UInt32?\n\n public init(hcsHandles: UInt32?, hcaObjects: UInt32?) {\n self.hcsHandles = hcsHandles\n self.hcaObjects = hcaObjects\n }\n}\n\npublic struct LinuxResources: Codable, Sendable {\n public var devices: [LinuxDeviceCgroup]\n public var memory: LinuxMemory?\n public var cpu: LinuxCPU?\n public var pids: LinuxPids?\n public var blockIO: LinuxBlockIO?\n public var hugepageLimits: [LinuxHugepageLimit]\n public var network: LinuxNetwork?\n public var rdma: [String: LinuxRdma]?\n public var unified: [String: String]?\n\n public init(\n devices: [LinuxDeviceCgroup] = [],\n memory: LinuxMemory? = nil,\n cpu: LinuxCPU? = nil,\n pids: LinuxPids? = nil,\n blockIO: LinuxBlockIO? = nil,\n hugepageLimits: [LinuxHugepageLimit] = [],\n network: LinuxNetwork? = nil,\n rdma: [String: LinuxRdma]? = nil,\n unified: [String: String] = [:]\n ) {\n self.devices = devices\n self.memory = memory\n self.cpu = cpu\n self.pids = pids\n self.blockIO = blockIO\n self.hugepageLimits = hugepageLimits\n self.network = network\n self.rdma = rdma\n self.unified = unified\n }\n}\n\npublic struct LinuxDevice: Codable, Sendable {\n public var path: String\n public var type: String\n public var major: Int64\n public var minor: Int64\n public var fileMode: UInt32?\n public var uid: UInt32?\n public var gid: UInt32?\n\n public init(\n path: String,\n type: String,\n major: Int64,\n minor: Int64,\n fileMode: UInt32?,\n uid: UInt32?,\n gid: UInt32?\n ) {\n self.path = path\n self.type = type\n self.major = major\n self.minor = minor\n self.fileMode = fileMode\n self.uid = uid\n self.gid = gid\n }\n}\n\npublic struct LinuxDeviceCgroup: Codable, Sendable {\n public var allow: Bool\n public var type: String\n public var major: Int64?\n public var minor: Int64?\n public var access: String?\n\n public init(allow: Bool, type: String, major: Int64?, minor: Int64?, access: String?) {\n self.allow = allow\n self.type = type\n self.major = major\n self.minor = minor\n self.access = access\n }\n}\n\npublic enum LinuxPersonalityDomain: String, Codable, Sendable {\n case perLinux = \"LINUX\"\n case perLinux32 = \"LINUX32\"\n}\n\npublic struct LinuxPersonality: Codable, Sendable {\n public var domain: LinuxPersonalityDomain\n public var flags: [String]\n\n public init(domain: LinuxPersonalityDomain, flags: [String]) {\n self.domain = domain\n self.flags = flags\n }\n}\n\npublic struct LinuxSeccomp: Codable, Sendable {\n public var defaultAction: LinuxSeccompAction\n public var defaultErrnoRet: UInt?\n public var architectures: [Arch]\n public var flags: [LinuxSeccompFlag]\n public var listenerPath: String\n public var listenerMetadata: String\n public var syscalls: [LinuxSyscall]\n\n public init(\n defaultAction: LinuxSeccompAction,\n defaultErrnoRet: UInt?,\n architectures: [Arch],\n flags: [LinuxSeccompFlag],\n listenerPath: String,\n listenerMetadata: String,\n syscalls: [LinuxSyscall]\n ) {\n self.defaultAction = defaultAction\n self.defaultErrnoRet = defaultErrnoRet\n self.architectures = architectures\n self.flags = flags\n self.listenerPath = listenerPath\n self.listenerMetadata = listenerMetadata\n self.syscalls = syscalls\n }\n}\n\npublic enum LinuxSeccompFlag: String, Codable, Sendable {\n case flagLog = \"SECCOMP_FILTER_FLAG_LOG\"\n case flagSpecAllow = \"SECCOMP_FILTER_FLAG_SPEC_ALLOW\"\n case flagWaitKillableRecv = \"SECCOMP_FILTER_FLAG_WAIT_KILLABLE_RECV\"\n}\n\npublic enum Arch: String, Codable, Sendable {\n case archX86 = \"SCMP_ARCH_X86\"\n case archX86_64 = \"SCMP_ARCH_X86_64\"\n case archX32 = \"SCMP_ARCH_X32\"\n case archARM = \"SCMP_ARCH_ARM\"\n case archAARCH64 = \"SCMP_ARCH_AARCH64\"\n case archMIPS = \"SCMP_ARCH_MIPS\"\n case archMIPS64 = \"SCMP_ARCH_MIPS64\"\n case archMIPS64N32 = \"SCMP_ARCH_MIPS64N32\"\n case archMIPSEL = \"SCMP_ARCH_MIPSEL\"\n case archMIPSEL64 = \"SCMP_ARCH_MIPSEL64\"\n case archMIPSEL64N32 = \"SCMP_ARCH_MIPSEL64N32\"\n case archPPC = \"SCMP_ARCH_PPC\"\n case archPPC64 = \"SCMP_ARCH_PPC64\"\n case archPPC64LE = \"SCMP_ARCH_PPC64LE\"\n case archS390 = \"SCMP_ARCH_S390\"\n case archS390X = \"SCMP_ARCH_S390X\"\n case archPARISC = \"SCMP_ARCH_PARISC\"\n case archPARISC64 = \"SCMP_ARCH_PARISC64\"\n case archRISCV64 = \"SCMP_ARCH_RISCV64\"\n}\n\npublic enum LinuxSeccompAction: String, Codable, Sendable {\n case actKill = \"SCMP_ACT_KILL\"\n case actKillProcess = \"SCMP_ACT_KILL_PROCESS\"\n case actKillThread = \"SCMP_ACT_KILL_THREAD\"\n case actTrap = \"SCMP_ACT_TRAP\"\n case actErrno = \"SCMP_ACT_ERRNO\"\n case actTrace = \"SCMP_ACT_TRACE\"\n case actAllow = \"SCMP_ACT_ALLOW\"\n case actLog = \"SCMP_ACT_LOG\"\n case actNotify = \"SCMP_ACT_NOTIFY\"\n}\n\npublic enum LinuxSeccompOperator: String, Codable, Sendable {\n case opNotEqual = \"SCMP_CMP_NE\"\n case opLessThan = \"SCMP_CMP_LT\"\n case opLessEqual = \"SCMP_CMP_LE\"\n case opEqualTo = \"SCMP_CMP_EQ\"\n case opGreaterEqual = \"SCMP_CMP_GE\"\n case opGreaterThan = \"SCMP_CMP_GT\"\n case opMaskedEqual = \"SCMP_CMP_MASKED_EQ\"\n}\n\npublic struct LinuxSeccompArg: Codable, Sendable {\n public var index: UInt\n public var value: UInt64\n public var valueTwo: UInt64\n public var op: LinuxSeccompOperator\n\n public init(index: UInt, value: UInt64, valueTwo: UInt64, op: LinuxSeccompOperator) {\n self.index = index\n self.value = value\n self.valueTwo = valueTwo\n self.op = op\n }\n}\n\npublic struct LinuxSyscall: Codable, Sendable {\n public var names: [String]\n public var action: LinuxSeccompAction\n public var errnoRet: UInt?\n public var args: [LinuxSeccompArg]\n\n public init(\n names: [String],\n action: LinuxSeccompAction,\n errnoRet: UInt?,\n args: [LinuxSeccompArg]\n ) {\n self.names = names\n self.action = action\n self.errnoRet = errnoRet\n self.args = args\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Terminal.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// `Terminal` provides a clean interface to deal with terminal interactions on Unix platforms.\npublic struct Terminal: Sendable {\n private let initState: termios?\n\n private var descriptor: Int32 {\n handle.fileDescriptor\n }\n public let handle: FileHandle\n\n public init(descriptor: Int32, setInitState: Bool = true) throws {\n if setInitState {\n self.initState = try Self.getattr(descriptor)\n } else {\n initState = nil\n }\n self.handle = .init(fileDescriptor: descriptor, closeOnDealloc: false)\n }\n\n /// Write the provided data to the tty device.\n public func write(_ data: Data) throws {\n try handle.write(contentsOf: data)\n }\n\n /// The winsize for a pty.\n public struct Size: Sendable {\n let size: winsize\n\n /// The width or `col` of the pty.\n public var width: UInt16 {\n size.ws_col\n }\n /// The height or `rows` of the pty.\n public var height: UInt16 {\n size.ws_row\n }\n\n init(_ size: winsize) {\n self.size = size\n }\n\n /// Set the size for use with a pty.\n public init(width cols: UInt16, height rows: UInt16) {\n self.size = winsize(ws_row: rows, ws_col: cols, ws_xpixel: 0, ws_ypixel: 0)\n }\n }\n\n /// Return the current pty attached to any of the STDIO descriptors.\n public static var current: Terminal {\n get throws {\n for i in [STDERR_FILENO, STDOUT_FILENO, STDIN_FILENO] {\n do {\n return try Terminal(descriptor: i)\n } catch {}\n }\n throw Error.notAPty\n }\n }\n\n /// The current window size for the pty.\n public var size: Size {\n get throws {\n var ws = winsize()\n try fromSyscall(ioctl(descriptor, UInt(TIOCGWINSZ), &ws))\n return Size(ws)\n }\n }\n\n /// Create a new pty pair.\n /// - Parameter initialSize: An initial size of the child pty.\n public static func create(initialSize: Size? = nil) throws -> (parent: Terminal, child: Terminal) {\n var parent: Int32 = 0\n var child: Int32 = 0\n let size = initialSize ?? Size(width: 120, height: 40)\n var ws = size.size\n\n try fromSyscall(openpty(&parent, &child, nil, nil, &ws))\n return (\n parent: try Terminal(descriptor: parent, setInitState: false),\n child: try Terminal(descriptor: child, setInitState: false)\n )\n }\n}\n\n// MARK: Errors\n\nextension Terminal {\n public enum Error: Swift.Error, CustomStringConvertible {\n case notAPty\n\n public var description: String {\n switch self {\n case .notAPty:\n return \"the provided fd is not a pty\"\n }\n }\n }\n}\n\nextension Terminal {\n /// Resize the current pty from the size of the provided pty.\n /// - Parameter pty: A pty to resize from.\n public func resize(from pty: Terminal) throws {\n var ws = try pty.size\n try fromSyscall(ioctl(descriptor, UInt(TIOCSWINSZ), &ws))\n }\n\n /// Resize the pty to the provided window size.\n /// - Parameter size: A window size for a pty.\n public func resize(size: Size) throws {\n var ws = size.size\n try fromSyscall(ioctl(descriptor, UInt(TIOCSWINSZ), &ws))\n }\n\n /// Resize the pty to the provided window size.\n /// - Parameter width: A width or cols of the terminal.\n /// - Parameter height: A height or rows of the terminal.\n public func resize(width: UInt16, height: UInt16) throws {\n var ws = Size(width: width, height: height)\n try fromSyscall(ioctl(descriptor, UInt(TIOCSWINSZ), &ws))\n }\n}\n\nextension Terminal {\n /// Enable raw mode for the pty.\n public func setraw() throws {\n var attr = try Self.getattr(descriptor)\n cfmakeraw(&attr)\n attr.c_oflag = attr.c_oflag | tcflag_t(OPOST)\n try fromSyscall(tcsetattr(descriptor, TCSANOW, &attr))\n }\n\n /// Enable echo support.\n /// Chars typed will be displayed to the terminal.\n public func enableEcho() throws {\n var attr = try Self.getattr(descriptor)\n attr.c_iflag &= ~tcflag_t(ICRNL)\n attr.c_lflag &= ~tcflag_t(ICANON | ECHO)\n try fromSyscall(tcsetattr(descriptor, TCSANOW, &attr))\n }\n\n /// Disable echo support.\n /// Chars typed will not be displayed back to the terminal.\n public func disableEcho() throws {\n var attr = try Self.getattr(descriptor)\n attr.c_lflag &= ~tcflag_t(ECHO)\n try fromSyscall(tcsetattr(descriptor, TCSANOW, &attr))\n }\n\n private static func getattr(_ fd: Int32) throws -> termios {\n var attr = termios()\n try fromSyscall(tcgetattr(fd, &attr))\n return attr\n }\n}\n\n// MARK: Reset\n\nextension Terminal {\n /// Close this pty's file descriptor.\n public func close() throws {\n do {\n // Use FileHandle's close directly as it sets the underlying fd in the object\n // to -1 for us.\n try self.handle.close()\n } catch {\n if let error = error as NSError?, error.domain == NSPOSIXErrorDomain {\n throw POSIXError(.init(rawValue: Int32(error.code))!)\n }\n throw error\n }\n }\n\n /// Reset the pty to its initial state.\n public func reset() throws {\n if var attr = initState {\n try fromSyscall(tcsetattr(descriptor, TCSANOW, &attr))\n }\n }\n\n /// Reset the pty to its initial state masking any errors.\n /// This is commonly used in a `defer` body to reset the current pty where the error code is not generally useful.\n public func tryReset() {\n try? reset()\n }\n}\n\nprivate func fromSyscall(_ status: Int32) throws {\n guard status == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/AddressAllocator.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Conforming objects can allocate and free various address types.\npublic protocol AddressAllocator: Sendable {\n associatedtype AddressType: Sendable\n\n /// Allocate a new address.\n func allocate() throws -> AddressType\n\n /// Attempt to reserve a specific address.\n func reserve(_ address: AddressType) throws\n\n /// Free an allocated address.\n func release(_ address: AddressType) throws\n\n /// If no addresses are allocated, prevent future allocations and return true.\n func disableAllocator() -> Bool\n}\n\n/// Errors that a type implementing AddressAllocator should throw.\npublic enum AllocatorError: Swift.Error, CustomStringConvertible, Equatable {\n case allocatorDisabled\n case allocatorFull\n case alreadyAllocated(_ address: String)\n case invalidAddress(_ index: String)\n case invalidArgument(_ msg: String)\n case invalidIndex(_ index: Int)\n case notAllocated(_ address: String)\n case rangeExceeded\n\n public var description: String {\n switch self {\n case .allocatorDisabled:\n return \"the allocator is shutting down\"\n case .allocatorFull:\n return \"no free indices are available for allocation\"\n case .alreadyAllocated(let address):\n return \"cannot choose already-allocated address \\(address)\"\n case .invalidAddress(let address):\n return \"cannot create index using address \\(address)\"\n case .invalidArgument(let msg):\n return \"invalid argument: \\(msg)\"\n case .invalidIndex(let index):\n return \"cannot create address using index \\(index)\"\n case .notAllocated(let address):\n return \"cannot free unallocated address \\(address)\"\n case .rangeExceeded:\n return \"cannot create allocator that overflows maximum address value\"\n }\n }\n}\n"], ["/containerization/Sources/SendablePropertyMacros/SendablePropertyMacroUnchecked.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SwiftCompilerPlugin\nimport SwiftParser\nimport SwiftSyntax\nimport SwiftSyntaxBuilder\nimport SwiftSyntaxMacros\n\n/// A macro that allows to make a property of a custom type thread-safe keeping the `Sendable` conformance of the type. This macro can be used with classes and enums. Avoid using it with structs, arrays, and dictionaries.\npublic struct SendablePropertyMacroUnchecked: PeerMacro {\n private static func peerPropertyName(for propertyName: String) -> String {\n \"_\" + propertyName\n }\n\n /// The macro expansion that introduces a `Sendable`-conforming \"peer\" declaration for a thread-safe storage for the value of the given declaration of a variable.\n /// - Parameters:\n /// - node: The given attribute node.\n /// - declaration: The given declaration.\n /// - context: The macro expansion context.\n public static func expansion(\n of node: SwiftSyntax.AttributeSyntax, providingPeersOf declaration: some SwiftSyntax.DeclSyntaxProtocol, in context: some SwiftSyntaxMacros.MacroExpansionContext\n ) throws -> [SwiftSyntax.DeclSyntax] {\n guard let varDecl = declaration.as(VariableDeclSyntax.self),\n let binding = varDecl.bindings.first,\n let pattern = binding.pattern.as(IdentifierPatternSyntax.self)\n else {\n throw SendablePropertyError.onlyApplicableToVar\n }\n\n let propertyName = pattern.identifier.text\n let hasInitializer = binding.initializer != nil\n let initializerValue = binding.initializer?.value.description ?? \"nil\"\n\n var genericTypeAnnotation = \"\"\n if let typeAnnotation = binding.typeAnnotation {\n let typeName = typeAnnotation.type.description.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)\n genericTypeAnnotation = \"<\\(typeName)\\(hasInitializer ? \"\" : \"?\")>\"\n }\n\n let accessLevel = varDecl.modifiers.first(where: { [\"open\", \"public\", \"internal\", \"fileprivate\", \"private\"].contains($0.name.text) })?.name.text ?? \"internal\"\n\n // Create a peer property\n let peerPropertyName = self.peerPropertyName(for: propertyName)\n let peerProperty: DeclSyntax =\n \"\"\"\n \\(raw: accessLevel) let \\(raw: peerPropertyName) = Synchronized\\(raw: genericTypeAnnotation)(\\(raw: initializerValue))\n \"\"\"\n return [peerProperty]\n }\n}\n\nextension SendablePropertyMacroUnchecked: AccessorMacro {\n /// The macro expansion that adds `Sendable`-conforming accessors to the given declaration of a variable.\n /// - Parameters:\n /// - node: The given attribute node.\n /// - declaration: The given declaration.\n /// - context: The macro expansion context.\n public static func expansion(\n of node: SwiftSyntax.AttributeSyntax, providingAccessorsOf declaration: some SwiftSyntax.DeclSyntaxProtocol, in context: some SwiftSyntaxMacros.MacroExpansionContext\n ) throws -> [SwiftSyntax.AccessorDeclSyntax] {\n guard let varDecl = declaration.as(VariableDeclSyntax.self),\n let binding = varDecl.bindings.first,\n let pattern = binding.pattern.as(IdentifierPatternSyntax.self)\n else {\n throw SendablePropertyError.onlyApplicableToVar\n }\n\n let propertyName = pattern.identifier.text\n let hasInitializer = binding.initializer != nil\n\n // Replace the property with an accessor\n let peerPropertyName = Self.peerPropertyName(for: propertyName)\n\n let accessorGetter: AccessorDeclSyntax =\n \"\"\"\n get {\n \\(raw: peerPropertyName).withLock { $0\\(raw: hasInitializer ? \"\" : \"!\") }\n }\n \"\"\"\n let accessorSetter: AccessorDeclSyntax =\n \"\"\"\n set {\n \\(raw: peerPropertyName).withLock { $0 = newValue }\n }\n \"\"\"\n\n return [accessorGetter, accessorSetter]\n }\n}\n"], ["/containerization/Sources/Containerization/Image/ImageStore/ImageStore+OCILayout.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\nextension ImageStore {\n /// Exports the specified images and their associated layers to an OCI Image Layout directory.\n /// This function saves the images identified by the `references` array, including their\n /// manifests and layer blobs, into a directory structure compliant with the OCI Image Layout specification at the given `out` URL.\n ///\n /// - Parameters:\n /// - references: A list image references that exists in the `ImageStore` that are to be saved in the OCI Image Layout format.\n /// - out: A URL to a directory on disk at which the OCI Image Layout structure will be created.\n /// - platform: An optional parameter to indicate the platform to be saved for the images.\n /// Defaults to `nil` signifying that layers for all supported platforms by the images will be saved.\n ///\n public func save(references: [String], out: URL, platform: Platform? = nil) async throws {\n let matcher = createPlatformMatcher(for: platform)\n let fileManager = FileManager.default\n let tempDir = fileManager.uniqueTemporaryDirectory()\n defer {\n try? fileManager.removeItem(at: tempDir)\n }\n\n var toSave: [Image] = []\n for reference in references {\n let image = try await self.get(reference: reference)\n let allowedMediaTypes = [MediaTypes.dockerManifestList, MediaTypes.index]\n guard allowedMediaTypes.contains(image.mediaType) else {\n throw ContainerizationError(.internalError, message: \"Cannot save image \\(image.reference) with Index media type \\(image.mediaType)\")\n }\n toSave.append(image)\n }\n let client = try LocalOCILayoutClient(root: out)\n var saved: [Descriptor] = []\n\n for image in toSave {\n let ref = try Reference.parse(image.reference)\n let name = ref.path\n guard let tag = ref.tag ?? ref.digest else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid tag/digest for image reference \\(image.reference)\")\n }\n let operation = ExportOperation(name: name, tag: tag, contentStore: self.contentStore, client: client, progress: nil)\n var descriptor = try await operation.export(index: image.descriptor, platforms: matcher)\n client.setImageReferenceAnnotation(descriptor: &descriptor, reference: image.reference)\n saved.append(descriptor)\n }\n try client.createOCILayoutStructure(directory: out, manifests: saved)\n }\n\n /// Imports one or more images and their associated layers from an OCI Image Layout directory.\n ///\n /// - Parameters:\n /// - directory: A URL to a directory on disk at that follows the OCI Image Layout structure.\n /// - progress: An optional handler over which progress update events about the load operation can be received.\n /// - Returns: The list of images that were loaded into the `ImageStore`.\n ///\n public func load(from directory: URL, progress: ProgressHandler? = nil) async throws -> [Image] {\n let client = try LocalOCILayoutClient(root: directory)\n let index = try client.loadIndexFromOCILayout(directory: directory)\n let matcher = createPlatformMatcher(for: nil)\n\n var loaded: [Image.Description] = []\n let (id, tempDir) = try await self.contentStore.newIngestSession()\n do {\n for descriptor in index.manifests {\n guard let reference = client.getImageReferencefromDescriptor(descriptor: descriptor) else {\n continue\n }\n let ref = try Reference.parse(reference)\n let name = ref.path\n let operation = ImportOperation(name: name, contentStore: self.contentStore, client: client, ingestDir: tempDir, progress: progress)\n let indexDesc = try await operation.import(root: descriptor, matcher: matcher)\n loaded.append(Image.Description(reference: reference, descriptor: indexDesc))\n }\n\n let loadedImages = loaded\n let importedImages = try await self.lock.withLock { lock in\n var images: [Image] = []\n try await self.contentStore.completeIngestSession(id)\n for description in loadedImages {\n let img = try await self._create(description: description, lock: lock)\n images.append(img)\n }\n return images\n }\n guard importedImages.count > 0 else {\n throw ContainerizationError(.internalError, message: \"Failed to import image\")\n }\n return importedImages\n } catch {\n try? await self.contentStore.cancelIngestSession(id)\n throw error\n }\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/Application.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport NIOCore\nimport NIOPosix\n\n#if os(Linux)\nimport Musl\nimport LCShim\n#endif\n\n@main\nstruct Application {\n private static let foregroundEnvVar = \"FOREGROUND\"\n private static let vsockPort = 1024\n private static let standardErrorLock = NSLock()\n\n private static func runInForeground(_ log: Logger) throws {\n log.info(\"running vminitd under pid1\")\n\n var command = Command(\"/sbin/vminitd\")\n command.attrs = .init(setsid: true)\n command.stdin = .standardInput\n command.stdout = .standardOutput\n command.stderr = .standardError\n command.environment = [\"\\(foregroundEnvVar)=1\"]\n\n try command.start()\n _ = try command.wait()\n }\n\n private static func adjustLimits() throws {\n var limits = rlimit()\n guard getrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n limits.rlim_cur = 65536\n limits.rlim_max = 65536\n guard setrlimit(RLIMIT_NOFILE, &limits) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n }\n\n @Sendable\n private static func standardError(label: String) -> StreamLogHandler {\n standardErrorLock.withLock {\n StreamLogHandler.standardError(label: label)\n }\n }\n\n static func main() async throws {\n LoggingSystem.bootstrap(standardError)\n var log = Logger(label: \"vminitd\")\n\n try adjustLimits()\n\n // when running under debug mode, launch vminitd as a sub process of pid1\n // so that we get a chance to collect better logs and errors before pid1 exists\n // and the kernel panics.\n #if DEBUG\n let environment = ProcessInfo.processInfo.environment\n let foreground = environment[Self.foregroundEnvVar]\n log.info(\"checking for shim var \\(foregroundEnvVar)=\\(String(describing: foreground))\")\n\n if foreground == nil {\n try runInForeground(log)\n exit(0)\n }\n\n // since we are not running as pid1 in this mode we must set ourselves\n // as a subpreaper so that all child processes are reaped by us and not\n // passed onto our parent.\n CZ_set_sub_reaper()\n #endif\n\n signal(SIGPIPE, SIG_IGN)\n\n // Because the sysctl rpc wouldn't make sense if this didn't always exist, we\n // ALWAYS mount /proc.\n guard Musl.mount(\"proc\", \"/proc\", \"proc\", 0, \"\") == 0 else {\n log.error(\"failed to mount /proc\")\n exit(1)\n }\n\n try Binfmt.mount()\n\n log.logLevel = .debug\n\n log.info(\"vminitd booting...\")\n let eg = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)\n let server = Initd(log: log, group: eg)\n\n do {\n log.info(\"serve vminitd api\")\n try await server.serve(port: vsockPort)\n log.info(\"vminitd api returned...\")\n } catch {\n log.error(\"vminitd boot error \\(error)\")\n exit(1)\n }\n }\n}\n"], ["/containerization/Sources/Containerization/SandboxContext/SandboxContext.pb.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// DO NOT EDIT.\n// swift-format-ignore-file\n// swiftlint:disable all\n//\n// Generated by the Swift generator plugin for the protocol buffer compiler.\n// Source: SandboxContext.proto\n//\n// For information on using the generated types, please see the documentation:\n// https://github.com/apple/swift-protobuf/\n\nimport Foundation\nimport SwiftProtobuf\n\n// If the compiler emits an error on this type, it is because this file\n// was generated by a version of the `protoc` Swift plug-in that is\n// incompatible with the version of SwiftProtobuf to which you are linking.\n// Please ensure that you are building against the same version of the API\n// that was used to generate this file.\nfileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {\n struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}\n typealias Version = _2\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_Stdio: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var stdinPort: Int32 {\n get {return _stdinPort ?? 0}\n set {_stdinPort = newValue}\n }\n /// Returns true if `stdinPort` has been explicitly set.\n public var hasStdinPort: Bool {return self._stdinPort != nil}\n /// Clears the value of `stdinPort`. Subsequent reads from it will return its default value.\n public mutating func clearStdinPort() {self._stdinPort = nil}\n\n public var stdoutPort: Int32 {\n get {return _stdoutPort ?? 0}\n set {_stdoutPort = newValue}\n }\n /// Returns true if `stdoutPort` has been explicitly set.\n public var hasStdoutPort: Bool {return self._stdoutPort != nil}\n /// Clears the value of `stdoutPort`. Subsequent reads from it will return its default value.\n public mutating func clearStdoutPort() {self._stdoutPort = nil}\n\n public var stderrPort: Int32 {\n get {return _stderrPort ?? 0}\n set {_stderrPort = newValue}\n }\n /// Returns true if `stderrPort` has been explicitly set.\n public var hasStderrPort: Bool {return self._stderrPort != nil}\n /// Clears the value of `stderrPort`. Subsequent reads from it will return its default value.\n public mutating func clearStderrPort() {self._stderrPort = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _stdinPort: Int32? = nil\n fileprivate var _stdoutPort: Int32? = nil\n fileprivate var _stderrPort: Int32? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var binaryPath: String = String()\n\n public var name: String = String()\n\n public var type: String = String()\n\n public var offset: String = String()\n\n public var magic: String = String()\n\n public var mask: String = String()\n\n public var flags: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetTimeRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var sec: Int64 = 0\n\n public var usec: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetTimeResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SysctlRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var settings: Dictionary = [:]\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SysctlResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var vsockPort: UInt32 = 0\n\n public var guestPath: String = String()\n\n public var guestSocketPermissions: UInt32 {\n get {return _guestSocketPermissions ?? 0}\n set {_guestSocketPermissions = newValue}\n }\n /// Returns true if `guestSocketPermissions` has been explicitly set.\n public var hasGuestSocketPermissions: Bool {return self._guestSocketPermissions != nil}\n /// Clears the value of `guestSocketPermissions`. Subsequent reads from it will return its default value.\n public mutating func clearGuestSocketPermissions() {self._guestSocketPermissions = nil}\n\n public var action: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest.Action = .into\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public enum Action: SwiftProtobuf.Enum, Swift.CaseIterable {\n public typealias RawValue = Int\n case into // = 0\n case outOf // = 1\n case UNRECOGNIZED(Int)\n\n public init() {\n self = .into\n }\n\n public init?(rawValue: Int) {\n switch rawValue {\n case 0: self = .into\n case 1: self = .outOf\n default: self = .UNRECOGNIZED(rawValue)\n }\n }\n\n public var rawValue: Int {\n switch self {\n case .into: return 0\n case .outOf: return 1\n case .UNRECOGNIZED(let i): return i\n }\n }\n\n // The compiler won't synthesize support with the UNRECOGNIZED case.\n public static let allCases: [Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest.Action] = [\n .into,\n .outOf,\n ]\n\n }\n\n public init() {}\n\n fileprivate var _guestSocketPermissions: UInt32? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_MountRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var type: String = String()\n\n public var source: String = String()\n\n public var destination: String = String()\n\n public var options: [String] = []\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_MountResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_UmountRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var path: String = String()\n\n public var flags: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_UmountResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetenvRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var key: String = String()\n\n public var value: String {\n get {return _value ?? String()}\n set {_value = newValue}\n }\n /// Returns true if `value` has been explicitly set.\n public var hasValue: Bool {return self._value != nil}\n /// Clears the value of `value`. Subsequent reads from it will return its default value.\n public mutating func clearValue() {self._value = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _value: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SetenvResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_GetenvRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var key: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_GetenvResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var value: String {\n get {return _value ?? String()}\n set {_value = newValue}\n }\n /// Returns true if `value` has been explicitly set.\n public var hasValue: Bool {return self._value != nil}\n /// Clears the value of `value`. Subsequent reads from it will return its default value.\n public mutating func clearValue() {self._value = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _value: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest: @unchecked Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var stdin: UInt32 {\n get {return _stdin ?? 0}\n set {_stdin = newValue}\n }\n /// Returns true if `stdin` has been explicitly set.\n public var hasStdin: Bool {return self._stdin != nil}\n /// Clears the value of `stdin`. Subsequent reads from it will return its default value.\n public mutating func clearStdin() {self._stdin = nil}\n\n public var stdout: UInt32 {\n get {return _stdout ?? 0}\n set {_stdout = newValue}\n }\n /// Returns true if `stdout` has been explicitly set.\n public var hasStdout: Bool {return self._stdout != nil}\n /// Clears the value of `stdout`. Subsequent reads from it will return its default value.\n public mutating func clearStdout() {self._stdout = nil}\n\n public var stderr: UInt32 {\n get {return _stderr ?? 0}\n set {_stderr = newValue}\n }\n /// Returns true if `stderr` has been explicitly set.\n public var hasStderr: Bool {return self._stderr != nil}\n /// Clears the value of `stderr`. Subsequent reads from it will return its default value.\n public mutating func clearStderr() {self._stderr = nil}\n\n public var configuration: Data = Data()\n\n public var options: Data {\n get {return _options ?? Data()}\n set {_options = newValue}\n }\n /// Returns true if `options` has been explicitly set.\n public var hasOptions: Bool {return self._options != nil}\n /// Clears the value of `options`. Subsequent reads from it will return its default value.\n public mutating func clearOptions() {self._options = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n fileprivate var _stdin: UInt32? = nil\n fileprivate var _stdout: UInt32? = nil\n fileprivate var _stderr: UInt32? = nil\n fileprivate var _options: Data? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var exitCode: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var rows: UInt32 = 0\n\n public var columns: UInt32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_StartProcessRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_StartProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var pid: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_KillProcessRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var signal: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_KillProcessResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var result: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var id: String = String()\n\n public var containerID: String {\n get {return _containerID ?? String()}\n set {_containerID = newValue}\n }\n /// Returns true if `containerID` has been explicitly set.\n public var hasContainerID: Bool {return self._containerID != nil}\n /// Clears the value of `containerID`. Subsequent reads from it will return its default value.\n public mutating func clearContainerID() {self._containerID = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _containerID: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_MkdirRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var path: String = String()\n\n public var all: Bool = false\n\n public var perms: UInt32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_MkdirResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var interface: String = String()\n\n public var up: Bool = false\n\n public var mtu: UInt32 {\n get {return _mtu ?? 0}\n set {_mtu = newValue}\n }\n /// Returns true if `mtu` has been explicitly set.\n public var hasMtu: Bool {return self._mtu != nil}\n /// Clears the value of `mtu`. Subsequent reads from it will return its default value.\n public mutating func clearMtu() {self._mtu = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _mtu: UInt32? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var interface: String = String()\n\n public var address: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var interface: String = String()\n\n public var address: String = String()\n\n public var srcAddr: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var interface: String = String()\n\n public var gateway: String = String()\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var location: String = String()\n\n public var nameservers: [String] = []\n\n public var domain: String {\n get {return _domain ?? String()}\n set {_domain = newValue}\n }\n /// Returns true if `domain` has been explicitly set.\n public var hasDomain: Bool {return self._domain != nil}\n /// Clears the value of `domain`. Subsequent reads from it will return its default value.\n public mutating func clearDomain() {self._domain = nil}\n\n public var searchDomains: [String] = []\n\n public var options: [String] = []\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _domain: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var location: String = String()\n\n public var entries: [Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.HostsEntry] = []\n\n public var comment: String {\n get {return _comment ?? String()}\n set {_comment = newValue}\n }\n /// Returns true if `comment` has been explicitly set.\n public var hasComment: Bool {return self._comment != nil}\n /// Clears the value of `comment`. Subsequent reads from it will return its default value.\n public mutating func clearComment() {self._comment = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public struct HostsEntry: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var ipAddress: String = String()\n\n public var hostnames: [String] = []\n\n public var comment: String {\n get {return _comment ?? String()}\n set {_comment = newValue}\n }\n /// Returns true if `comment` has been explicitly set.\n public var hasComment: Bool {return self._comment != nil}\n /// Clears the value of `comment`. Subsequent reads from it will return its default value.\n public mutating func clearComment() {self._comment = nil}\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n\n fileprivate var _comment: String? = nil\n }\n\n public init() {}\n\n fileprivate var _comment: String? = nil\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SyncRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_SyncResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_KillRequest: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var pid: Int32 = 0\n\n public var signal: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\npublic struct Com_Apple_Containerization_Sandbox_V3_KillResponse: Sendable {\n // SwiftProtobuf.Message conformance is added in an extension below. See the\n // `Message` and `Message+*Additions` files in the SwiftProtobuf library for\n // methods supported on all messages.\n\n public var result: Int32 = 0\n\n public var unknownFields = SwiftProtobuf.UnknownStorage()\n\n public init() {}\n}\n\n// MARK: - Code below here is support for the SwiftProtobuf runtime.\n\nfileprivate let _protobuf_package = \"com.apple.containerization.sandbox.v3\"\n\nextension Com_Apple_Containerization_Sandbox_V3_Stdio: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".Stdio\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"stdinPort\"),\n 2: .same(proto: \"stdoutPort\"),\n 3: .same(proto: \"stderrPort\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self._stdinPort) }()\n case 2: try { try decoder.decodeSingularInt32Field(value: &self._stdoutPort) }()\n case 3: try { try decoder.decodeSingularInt32Field(value: &self._stderrPort) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n try { if let v = self._stdinPort {\n try visitor.visitSingularInt32Field(value: v, fieldNumber: 1)\n } }()\n try { if let v = self._stdoutPort {\n try visitor.visitSingularInt32Field(value: v, fieldNumber: 2)\n } }()\n try { if let v = self._stderrPort {\n try visitor.visitSingularInt32Field(value: v, fieldNumber: 3)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_Stdio, rhs: Com_Apple_Containerization_Sandbox_V3_Stdio) -> Bool {\n if lhs._stdinPort != rhs._stdinPort {return false}\n if lhs._stdoutPort != rhs._stdoutPort {return false}\n if lhs._stderrPort != rhs._stderrPort {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetupEmulatorRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .standard(proto: \"binary_path\"),\n 2: .same(proto: \"name\"),\n 3: .same(proto: \"type\"),\n 4: .same(proto: \"offset\"),\n 5: .same(proto: \"magic\"),\n 6: .same(proto: \"mask\"),\n 7: .same(proto: \"flags\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.binaryPath) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.name) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.type) }()\n case 4: try { try decoder.decodeSingularStringField(value: &self.offset) }()\n case 5: try { try decoder.decodeSingularStringField(value: &self.magic) }()\n case 6: try { try decoder.decodeSingularStringField(value: &self.mask) }()\n case 7: try { try decoder.decodeSingularStringField(value: &self.flags) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.binaryPath.isEmpty {\n try visitor.visitSingularStringField(value: self.binaryPath, fieldNumber: 1)\n }\n if !self.name.isEmpty {\n try visitor.visitSingularStringField(value: self.name, fieldNumber: 2)\n }\n if !self.type.isEmpty {\n try visitor.visitSingularStringField(value: self.type, fieldNumber: 3)\n }\n if !self.offset.isEmpty {\n try visitor.visitSingularStringField(value: self.offset, fieldNumber: 4)\n }\n if !self.magic.isEmpty {\n try visitor.visitSingularStringField(value: self.magic, fieldNumber: 5)\n }\n if !self.mask.isEmpty {\n try visitor.visitSingularStringField(value: self.mask, fieldNumber: 6)\n }\n if !self.flags.isEmpty {\n try visitor.visitSingularStringField(value: self.flags, fieldNumber: 7)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest, rhs: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorRequest) -> Bool {\n if lhs.binaryPath != rhs.binaryPath {return false}\n if lhs.name != rhs.name {return false}\n if lhs.type != rhs.type {return false}\n if lhs.offset != rhs.offset {return false}\n if lhs.magic != rhs.magic {return false}\n if lhs.mask != rhs.mask {return false}\n if lhs.flags != rhs.flags {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetupEmulatorResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse, rhs: Com_Apple_Containerization_Sandbox_V3_SetupEmulatorResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetTimeRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetTimeRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"sec\"),\n 2: .same(proto: \"usec\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt64Field(value: &self.sec) }()\n case 2: try { try decoder.decodeSingularInt32Field(value: &self.usec) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.sec != 0 {\n try visitor.visitSingularInt64Field(value: self.sec, fieldNumber: 1)\n }\n if self.usec != 0 {\n try visitor.visitSingularInt32Field(value: self.usec, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest, rhs: Com_Apple_Containerization_Sandbox_V3_SetTimeRequest) -> Bool {\n if lhs.sec != rhs.sec {return false}\n if lhs.usec != rhs.usec {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetTimeResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetTimeResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetTimeResponse, rhs: Com_Apple_Containerization_Sandbox_V3_SetTimeResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SysctlRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SysctlRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"settings\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.settings) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.settings.isEmpty {\n try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.settings, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SysctlRequest, rhs: Com_Apple_Containerization_Sandbox_V3_SysctlRequest) -> Bool {\n if lhs.settings != rhs.settings {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SysctlResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SysctlResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SysctlResponse, rhs: Com_Apple_Containerization_Sandbox_V3_SysctlResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ProxyVsockRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .standard(proto: \"vsock_port\"),\n 3: .same(proto: \"guestPath\"),\n 4: .same(proto: \"guestSocketPermissions\"),\n 5: .same(proto: \"action\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularUInt32Field(value: &self.vsockPort) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.guestPath) }()\n case 4: try { try decoder.decodeSingularUInt32Field(value: &self._guestSocketPermissions) }()\n case 5: try { try decoder.decodeSingularEnumField(value: &self.action) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n if self.vsockPort != 0 {\n try visitor.visitSingularUInt32Field(value: self.vsockPort, fieldNumber: 2)\n }\n if !self.guestPath.isEmpty {\n try visitor.visitSingularStringField(value: self.guestPath, fieldNumber: 3)\n }\n try { if let v = self._guestSocketPermissions {\n try visitor.visitSingularUInt32Field(value: v, fieldNumber: 4)\n } }()\n if self.action != .into {\n try visitor.visitSingularEnumField(value: self.action, fieldNumber: 5)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest, rhs: Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.vsockPort != rhs.vsockPort {return false}\n if lhs.guestPath != rhs.guestPath {return false}\n if lhs._guestSocketPermissions != rhs._guestSocketPermissions {return false}\n if lhs.action != rhs.action {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest.Action: SwiftProtobuf._ProtoNameProviding {\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 0: .same(proto: \"INTO\"),\n 1: .same(proto: \"OUT_OF\"),\n ]\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ProxyVsockResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse, rhs: Com_Apple_Containerization_Sandbox_V3_ProxyVsockResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".StopVsockProxyRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest, rhs: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".StopVsockProxyResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse, rhs: Com_Apple_Containerization_Sandbox_V3_StopVsockProxyResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_MountRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".MountRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"type\"),\n 2: .same(proto: \"source\"),\n 3: .same(proto: \"destination\"),\n 4: .same(proto: \"options\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.type) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.source) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.destination) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.options) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.type.isEmpty {\n try visitor.visitSingularStringField(value: self.type, fieldNumber: 1)\n }\n if !self.source.isEmpty {\n try visitor.visitSingularStringField(value: self.source, fieldNumber: 2)\n }\n if !self.destination.isEmpty {\n try visitor.visitSingularStringField(value: self.destination, fieldNumber: 3)\n }\n if !self.options.isEmpty {\n try visitor.visitRepeatedStringField(value: self.options, fieldNumber: 4)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_MountRequest, rhs: Com_Apple_Containerization_Sandbox_V3_MountRequest) -> Bool {\n if lhs.type != rhs.type {return false}\n if lhs.source != rhs.source {return false}\n if lhs.destination != rhs.destination {return false}\n if lhs.options != rhs.options {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_MountResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".MountResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_MountResponse, rhs: Com_Apple_Containerization_Sandbox_V3_MountResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_UmountRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".UmountRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"path\"),\n 2: .same(proto: \"flags\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.path) }()\n case 2: try { try decoder.decodeSingularInt32Field(value: &self.flags) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.path.isEmpty {\n try visitor.visitSingularStringField(value: self.path, fieldNumber: 1)\n }\n if self.flags != 0 {\n try visitor.visitSingularInt32Field(value: self.flags, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_UmountRequest, rhs: Com_Apple_Containerization_Sandbox_V3_UmountRequest) -> Bool {\n if lhs.path != rhs.path {return false}\n if lhs.flags != rhs.flags {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_UmountResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".UmountResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_UmountResponse, rhs: Com_Apple_Containerization_Sandbox_V3_UmountResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetenvRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetenvRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"key\"),\n 2: .same(proto: \"value\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.key) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._value) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.key.isEmpty {\n try visitor.visitSingularStringField(value: self.key, fieldNumber: 1)\n }\n try { if let v = self._value {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetenvRequest, rhs: Com_Apple_Containerization_Sandbox_V3_SetenvRequest) -> Bool {\n if lhs.key != rhs.key {return false}\n if lhs._value != rhs._value {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SetenvResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SetenvResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SetenvResponse, rhs: Com_Apple_Containerization_Sandbox_V3_SetenvResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_GetenvRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".GetenvRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"key\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.key) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.key.isEmpty {\n try visitor.visitSingularStringField(value: self.key, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_GetenvRequest, rhs: Com_Apple_Containerization_Sandbox_V3_GetenvRequest) -> Bool {\n if lhs.key != rhs.key {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_GetenvResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".GetenvResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"value\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self._value) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n try { if let v = self._value {\n try visitor.visitSingularStringField(value: v, fieldNumber: 1)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_GetenvResponse, rhs: Com_Apple_Containerization_Sandbox_V3_GetenvResponse) -> Bool {\n if lhs._value != rhs._value {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CreateProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n 3: .same(proto: \"stdin\"),\n 4: .same(proto: \"stdout\"),\n 5: .same(proto: \"stderr\"),\n 6: .same(proto: \"configuration\"),\n 7: .same(proto: \"options\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n case 3: try { try decoder.decodeSingularUInt32Field(value: &self._stdin) }()\n case 4: try { try decoder.decodeSingularUInt32Field(value: &self._stdout) }()\n case 5: try { try decoder.decodeSingularUInt32Field(value: &self._stderr) }()\n case 6: try { try decoder.decodeSingularBytesField(value: &self.configuration) }()\n case 7: try { try decoder.decodeSingularBytesField(value: &self._options) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try { if let v = self._stdin {\n try visitor.visitSingularUInt32Field(value: v, fieldNumber: 3)\n } }()\n try { if let v = self._stdout {\n try visitor.visitSingularUInt32Field(value: v, fieldNumber: 4)\n } }()\n try { if let v = self._stderr {\n try visitor.visitSingularUInt32Field(value: v, fieldNumber: 5)\n } }()\n if !self.configuration.isEmpty {\n try visitor.visitSingularBytesField(value: self.configuration, fieldNumber: 6)\n }\n try { if let v = self._options {\n try visitor.visitSingularBytesField(value: v, fieldNumber: 7)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_CreateProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs._stdin != rhs._stdin {return false}\n if lhs._stdout != rhs._stdout {return false}\n if lhs._stderr != rhs._stderr {return false}\n if lhs.configuration != rhs.configuration {return false}\n if lhs._options != rhs._options {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CreateProcessResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_CreateProcessResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".WaitProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_WaitProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".WaitProcessResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"exitCode\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.exitCode) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.exitCode != 0 {\n try visitor.visitSingularInt32Field(value: self.exitCode, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_WaitProcessResponse) -> Bool {\n if lhs.exitCode != rhs.exitCode {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ResizeProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n 3: .same(proto: \"rows\"),\n 4: .same(proto: \"columns\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n case 3: try { try decoder.decodeSingularUInt32Field(value: &self.rows) }()\n case 4: try { try decoder.decodeSingularUInt32Field(value: &self.columns) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n if self.rows != 0 {\n try visitor.visitSingularUInt32Field(value: self.rows, fieldNumber: 3)\n }\n if self.columns != 0 {\n try visitor.visitSingularUInt32Field(value: self.columns, fieldNumber: 4)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_ResizeProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.rows != rhs.rows {return false}\n if lhs.columns != rhs.columns {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ResizeProcessResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_ResizeProcessResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".DeleteProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_DeleteProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".DeleteProcessResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_DeleteProcessResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_StartProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".StartProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_StartProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_StartProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".StartProcessResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"pid\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.pid) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.pid != 0 {\n try visitor.visitSingularInt32Field(value: self.pid, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_StartProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_StartProcessResponse) -> Bool {\n if lhs.pid != rhs.pid {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_KillProcessRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".KillProcessRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n 3: .same(proto: \"signal\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n case 3: try { try decoder.decodeSingularInt32Field(value: &self.signal) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n if self.signal != 0 {\n try visitor.visitSingularInt32Field(value: self.signal, fieldNumber: 3)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest, rhs: Com_Apple_Containerization_Sandbox_V3_KillProcessRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.signal != rhs.signal {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_KillProcessResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".KillProcessResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"result\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.result) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.result != 0 {\n try visitor.visitSingularInt32Field(value: self.result, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_KillProcessResponse, rhs: Com_Apple_Containerization_Sandbox_V3_KillProcessResponse) -> Bool {\n if lhs.result != rhs.result {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CloseProcessStdinRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"id\"),\n 2: .same(proto: \"containerID\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self._containerID) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.id.isEmpty {\n try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)\n }\n try { if let v = self._containerID {\n try visitor.visitSingularStringField(value: v, fieldNumber: 2)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest, rhs: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinRequest) -> Bool {\n if lhs.id != rhs.id {return false}\n if lhs._containerID != rhs._containerID {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".CloseProcessStdinResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse, rhs: Com_Apple_Containerization_Sandbox_V3_CloseProcessStdinResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_MkdirRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".MkdirRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"path\"),\n 2: .same(proto: \"all\"),\n 3: .same(proto: \"perms\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.path) }()\n case 2: try { try decoder.decodeSingularBoolField(value: &self.all) }()\n case 3: try { try decoder.decodeSingularUInt32Field(value: &self.perms) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.path.isEmpty {\n try visitor.visitSingularStringField(value: self.path, fieldNumber: 1)\n }\n if self.all != false {\n try visitor.visitSingularBoolField(value: self.all, fieldNumber: 2)\n }\n if self.perms != 0 {\n try visitor.visitSingularUInt32Field(value: self.perms, fieldNumber: 3)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_MkdirRequest, rhs: Com_Apple_Containerization_Sandbox_V3_MkdirRequest) -> Bool {\n if lhs.path != rhs.path {return false}\n if lhs.all != rhs.all {return false}\n if lhs.perms != rhs.perms {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_MkdirResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".MkdirResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_MkdirResponse, rhs: Com_Apple_Containerization_Sandbox_V3_MkdirResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpLinkSetRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"interface\"),\n 2: .same(proto: \"up\"),\n 3: .same(proto: \"mtu\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.interface) }()\n case 2: try { try decoder.decodeSingularBoolField(value: &self.up) }()\n case 3: try { try decoder.decodeSingularUInt32Field(value: &self._mtu) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.interface.isEmpty {\n try visitor.visitSingularStringField(value: self.interface, fieldNumber: 1)\n }\n if self.up != false {\n try visitor.visitSingularBoolField(value: self.up, fieldNumber: 2)\n }\n try { if let v = self._mtu {\n try visitor.visitSingularUInt32Field(value: v, fieldNumber: 3)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest, rhs: Com_Apple_Containerization_Sandbox_V3_IpLinkSetRequest) -> Bool {\n if lhs.interface != rhs.interface {return false}\n if lhs.up != rhs.up {return false}\n if lhs._mtu != rhs._mtu {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpLinkSetResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse, rhs: Com_Apple_Containerization_Sandbox_V3_IpLinkSetResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpAddrAddRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"interface\"),\n 2: .same(proto: \"address\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.interface) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.address) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.interface.isEmpty {\n try visitor.visitSingularStringField(value: self.interface, fieldNumber: 1)\n }\n if !self.address.isEmpty {\n try visitor.visitSingularStringField(value: self.address, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest, rhs: Com_Apple_Containerization_Sandbox_V3_IpAddrAddRequest) -> Bool {\n if lhs.interface != rhs.interface {return false}\n if lhs.address != rhs.address {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpAddrAddResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse, rhs: Com_Apple_Containerization_Sandbox_V3_IpAddrAddResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpRouteAddLinkRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"interface\"),\n 2: .same(proto: \"address\"),\n 3: .same(proto: \"srcAddr\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.interface) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.address) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self.srcAddr) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.interface.isEmpty {\n try visitor.visitSingularStringField(value: self.interface, fieldNumber: 1)\n }\n if !self.address.isEmpty {\n try visitor.visitSingularStringField(value: self.address, fieldNumber: 2)\n }\n if !self.srcAddr.isEmpty {\n try visitor.visitSingularStringField(value: self.srcAddr, fieldNumber: 3)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest, rhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkRequest) -> Bool {\n if lhs.interface != rhs.interface {return false}\n if lhs.address != rhs.address {return false}\n if lhs.srcAddr != rhs.srcAddr {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpRouteAddLinkResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse, rhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddLinkResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpRouteAddDefaultRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"interface\"),\n 2: .same(proto: \"gateway\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.interface) }()\n case 2: try { try decoder.decodeSingularStringField(value: &self.gateway) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if !self.interface.isEmpty {\n try visitor.visitSingularStringField(value: self.interface, fieldNumber: 1)\n }\n if !self.gateway.isEmpty {\n try visitor.visitSingularStringField(value: self.gateway, fieldNumber: 2)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest, rhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultRequest) -> Bool {\n if lhs.interface != rhs.interface {return false}\n if lhs.gateway != rhs.gateway {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".IpRouteAddDefaultResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse, rhs: Com_Apple_Containerization_Sandbox_V3_IpRouteAddDefaultResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ConfigureDnsRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"location\"),\n 2: .same(proto: \"nameservers\"),\n 3: .same(proto: \"domain\"),\n 4: .same(proto: \"searchDomains\"),\n 5: .same(proto: \"options\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.location) }()\n case 2: try { try decoder.decodeRepeatedStringField(value: &self.nameservers) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self._domain) }()\n case 4: try { try decoder.decodeRepeatedStringField(value: &self.searchDomains) }()\n case 5: try { try decoder.decodeRepeatedStringField(value: &self.options) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.location.isEmpty {\n try visitor.visitSingularStringField(value: self.location, fieldNumber: 1)\n }\n if !self.nameservers.isEmpty {\n try visitor.visitRepeatedStringField(value: self.nameservers, fieldNumber: 2)\n }\n try { if let v = self._domain {\n try visitor.visitSingularStringField(value: v, fieldNumber: 3)\n } }()\n if !self.searchDomains.isEmpty {\n try visitor.visitRepeatedStringField(value: self.searchDomains, fieldNumber: 4)\n }\n if !self.options.isEmpty {\n try visitor.visitRepeatedStringField(value: self.options, fieldNumber: 5)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest, rhs: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsRequest) -> Bool {\n if lhs.location != rhs.location {return false}\n if lhs.nameservers != rhs.nameservers {return false}\n if lhs._domain != rhs._domain {return false}\n if lhs.searchDomains != rhs.searchDomains {return false}\n if lhs.options != rhs.options {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ConfigureDnsResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse, rhs: Com_Apple_Containerization_Sandbox_V3_ConfigureDnsResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ConfigureHostsRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"location\"),\n 2: .same(proto: \"entries\"),\n 3: .same(proto: \"comment\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.location) }()\n case 2: try { try decoder.decodeRepeatedMessageField(value: &self.entries) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self._comment) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.location.isEmpty {\n try visitor.visitSingularStringField(value: self.location, fieldNumber: 1)\n }\n if !self.entries.isEmpty {\n try visitor.visitRepeatedMessageField(value: self.entries, fieldNumber: 2)\n }\n try { if let v = self._comment {\n try visitor.visitSingularStringField(value: v, fieldNumber: 3)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest, rhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest) -> Bool {\n if lhs.location != rhs.location {return false}\n if lhs.entries != rhs.entries {return false}\n if lhs._comment != rhs._comment {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.HostsEntry: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.protoMessageName + \".HostsEntry\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"ipAddress\"),\n 2: .same(proto: \"hostnames\"),\n 3: .same(proto: \"comment\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularStringField(value: &self.ipAddress) }()\n case 2: try { try decoder.decodeRepeatedStringField(value: &self.hostnames) }()\n case 3: try { try decoder.decodeSingularStringField(value: &self._comment) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every if/case branch local when no optimizations\n // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and\n // https://github.com/apple/swift-protobuf/issues/1182\n if !self.ipAddress.isEmpty {\n try visitor.visitSingularStringField(value: self.ipAddress, fieldNumber: 1)\n }\n if !self.hostnames.isEmpty {\n try visitor.visitRepeatedStringField(value: self.hostnames, fieldNumber: 2)\n }\n try { if let v = self._comment {\n try visitor.visitSingularStringField(value: v, fieldNumber: 3)\n } }()\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.HostsEntry, rhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsRequest.HostsEntry) -> Bool {\n if lhs.ipAddress != rhs.ipAddress {return false}\n if lhs.hostnames != rhs.hostnames {return false}\n if lhs._comment != rhs._comment {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".ConfigureHostsResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse, rhs: Com_Apple_Containerization_Sandbox_V3_ConfigureHostsResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SyncRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SyncRequest\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SyncRequest, rhs: Com_Apple_Containerization_Sandbox_V3_SyncRequest) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_SyncResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".SyncResponse\"\n public static let _protobuf_nameMap = SwiftProtobuf._NameMap()\n\n public mutating func decodeMessage(decoder: inout D) throws {\n // Load everything into unknown fields\n while try decoder.nextFieldNumber() != nil {}\n }\n\n public func traverse(visitor: inout V) throws {\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_SyncResponse, rhs: Com_Apple_Containerization_Sandbox_V3_SyncResponse) -> Bool {\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_KillRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".KillRequest\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"pid\"),\n 3: .same(proto: \"signal\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.pid) }()\n case 3: try { try decoder.decodeSingularInt32Field(value: &self.signal) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.pid != 0 {\n try visitor.visitSingularInt32Field(value: self.pid, fieldNumber: 1)\n }\n if self.signal != 0 {\n try visitor.visitSingularInt32Field(value: self.signal, fieldNumber: 3)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_KillRequest, rhs: Com_Apple_Containerization_Sandbox_V3_KillRequest) -> Bool {\n if lhs.pid != rhs.pid {return false}\n if lhs.signal != rhs.signal {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n\nextension Com_Apple_Containerization_Sandbox_V3_KillResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {\n public static let protoMessageName: String = _protobuf_package + \".KillResponse\"\n public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [\n 1: .same(proto: \"result\"),\n ]\n\n public mutating func decodeMessage(decoder: inout D) throws {\n while let fieldNumber = try decoder.nextFieldNumber() {\n // The use of inline closures is to circumvent an issue where the compiler\n // allocates stack space for every case branch when no optimizations are\n // enabled. https://github.com/apple/swift-protobuf/issues/1034\n switch fieldNumber {\n case 1: try { try decoder.decodeSingularInt32Field(value: &self.result) }()\n default: break\n }\n }\n }\n\n public func traverse(visitor: inout V) throws {\n if self.result != 0 {\n try visitor.visitSingularInt32Field(value: self.result, fieldNumber: 1)\n }\n try unknownFields.traverse(visitor: &visitor)\n }\n\n public static func ==(lhs: Com_Apple_Containerization_Sandbox_V3_KillResponse, rhs: Com_Apple_Containerization_Sandbox_V3_KillResponse) -> Bool {\n if lhs.result != rhs.result {return false}\n if lhs.unknownFields != rhs.unknownFields {return false}\n return true\n }\n}\n"], ["/containerization/Sources/Containerization/VirtualMachineAgent.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\n/// A protocol for the agent running inside a virtual machine. If an operation isn't\n/// supported the implementation MUST return a ContainerizationError with a code of\n/// `.unsupported`.\npublic protocol VirtualMachineAgent: Sendable {\n /// Perform a platform specific standard setup\n /// of the runtime environment.\n func standardSetup() async throws\n /// Close any resources held by the agent.\n func close() async throws\n\n // POSIX\n func getenv(key: String) async throws -> String\n func setenv(key: String, value: String) async throws\n func mount(_ mount: ContainerizationOCI.Mount) async throws\n func umount(path: String, flags: Int32) async throws\n func mkdir(path: String, all: Bool, perms: UInt32) async throws\n @discardableResult\n func kill(pid: Int32, signal: Int32) async throws -> Int32\n\n // Process lifecycle\n func createProcess(\n id: String,\n containerID: String?,\n stdinPort: UInt32?,\n stdoutPort: UInt32?,\n stderrPort: UInt32?,\n configuration: ContainerizationOCI.Spec,\n options: Data?\n ) async throws\n func startProcess(id: String, containerID: String?) async throws -> Int32\n func signalProcess(id: String, containerID: String?, signal: Int32) async throws\n func resizeProcess(id: String, containerID: String?, columns: UInt32, rows: UInt32) async throws\n func waitProcess(id: String, containerID: String?, timeoutInSeconds: Int64?) async throws -> Int32\n func deleteProcess(id: String, containerID: String?) async throws\n func closeProcessStdin(id: String, containerID: String?) async throws\n\n // Networking\n func up(name: String, mtu: UInt32?) async throws\n func down(name: String) async throws\n func addressAdd(name: String, address: String) async throws\n func routeAddDefault(name: String, gateway: String) async throws\n func configureDNS(config: DNS, location: String) async throws\n func configureHosts(config: Hosts, location: String) async throws\n}\n\nextension VirtualMachineAgent {\n public func closeProcessStdin(id: String, containerID: String?) async throws {\n throw ContainerizationError(.unsupported, message: \"closeProcessStdin\")\n }\n\n public func configureHosts(config: Hosts, location: String) async throws {\n throw ContainerizationError(.unsupported, message: \"configureHosts\")\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/ArchiveWriterConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CArchive\n\n/// Represents the configuration settings for an `ArchiveWriter`.\n///\n/// This struct allows specifying the archive format, compression filter,\n/// various format-specific options, and preferred locales for string encoding.\npublic struct ArchiveWriterConfiguration {\n /// The desired archive format\n public var format: Format\n /// The compression filter to apply to the archive\n public var filter: Filter\n /// An array of format-specific options to apply to the archive.\n /// This includes options like compression level and extended attribute format.\n public var options: [Options]\n /// An array of preferred locale identifiers for string encoding\n public var locales: [String]\n\n /// Initializes a new `ArchiveWriterConfiguration`.\n ///\n /// Sets up the configuration with the specified format, filter, options, and locales.\n public init(\n format: Format, filter: Filter, options: [Options] = [], locales: [String] = [\"en_US.UTF-8\", \"C.UTF-8\"]\n ) {\n self.format = format\n self.filter = filter\n self.options = options\n self.locales = locales\n }\n}\n\nextension ArchiveWriter {\n internal func setFormat(_ format: Format) throws {\n guard let underlying = self.underlying else { throw ArchiveError.noUnderlyingArchive }\n let r = archive_write_set_format(underlying, format.code)\n guard r == ARCHIVE_OK else { throw ArchiveError.unableToSetFormat(r, format) }\n }\n\n internal func addFilter(_ filter: Filter) throws {\n guard let underlying = self.underlying else { throw ArchiveError.noUnderlyingArchive }\n let r = archive_write_add_filter(underlying, filter.code)\n guard r == ARCHIVE_OK else { throw ArchiveError.unableToAddFilter(r, filter) }\n }\n\n internal func setOptions(_ options: [Options]) throws {\n try options.forEach {\n switch $0 {\n case .compressionLevel(let level):\n try wrap(\n archive_write_set_option(underlying, nil, \"compression-level\", \"\\(level)\"),\n ArchiveError.unableToSetOption, underlying: self.underlying)\n case .compression(.store):\n try wrap(\n archive_write_set_option(underlying, nil, \"compression\", \"store\"), ArchiveError.unableToSetOption,\n underlying: self.underlying)\n case .compression(.deflate):\n try wrap(\n archive_write_set_option(underlying, nil, \"compression\", \"deflate\"), ArchiveError.unableToSetOption,\n underlying: self.underlying)\n case .xattrformat(let value):\n let v = value.description\n try wrap(\n archive_write_set_option(underlying, nil, \"xattrheader\", v), ArchiveError.unableToSetOption,\n underlying: self.underlying)\n }\n }\n }\n}\n\npublic enum Options {\n case compressionLevel(UInt32)\n case compression(Compression)\n case xattrformat(XattrFormat)\n\n public enum Compression {\n case store\n case deflate\n }\n\n public enum XattrFormat: String, CustomStringConvertible {\n case schily\n case libarchive\n case all\n\n public var description: String {\n switch self {\n case .libarchive:\n return \"LIBARCHIVE\"\n case .schily:\n return \"SCHILY\"\n case .all:\n return \"ALL\"\n }\n }\n }\n}\n\n/// An enumeration of the supported archive formats.\npublic enum Format: String, Sendable {\n /// POSIX-standard `ustar` archives\n case ustar\n case gnutar\n /// POSIX `pax interchange format` archives\n case pax\n case paxRestricted\n /// POSIX octet-oriented cpio archives\n case cpio\n case cpioNewc\n /// Zip archive\n case zip\n /// two different variants of shar archives\n case shar\n case sharDump\n /// ISO9660 CD images\n case iso9660\n /// 7-Zip archives\n case sevenZip\n /// ar archives\n case arBSD\n case arGNU\n /// mtree file tree descriptions\n case mtree\n /// XAR archives\n case xar\n\n internal var code: CInt {\n switch self {\n case .ustar: return ARCHIVE_FORMAT_TAR_USTAR\n case .pax: return ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE\n case .paxRestricted: return ARCHIVE_FORMAT_TAR_PAX_RESTRICTED\n case .gnutar: return ARCHIVE_FORMAT_TAR_GNUTAR\n case .cpio: return ARCHIVE_FORMAT_CPIO_POSIX\n case .cpioNewc: return ARCHIVE_FORMAT_CPIO_AFIO_LARGE\n case .zip: return ARCHIVE_FORMAT_ZIP\n case .shar: return ARCHIVE_FORMAT_SHAR_BASE\n case .sharDump: return ARCHIVE_FORMAT_SHAR_DUMP\n case .iso9660: return ARCHIVE_FORMAT_ISO9660\n case .sevenZip: return ARCHIVE_FORMAT_7ZIP\n case .arBSD: return ARCHIVE_FORMAT_AR_BSD\n case .arGNU: return ARCHIVE_FORMAT_AR_GNU\n case .mtree: return ARCHIVE_FORMAT_MTREE\n case .xar: return ARCHIVE_FORMAT_XAR\n }\n }\n}\n\n/// An enumeration of the supported filters (compression / encoding standards) for an archive.\npublic enum Filter: String, Sendable {\n case none\n case gzip\n case bzip2\n case compress\n case lzma\n case xz\n case uu\n case rpm\n case lzip\n case lrzip\n case lzop\n case grzip\n case lz4\n\n internal var code: CInt {\n switch self {\n case .none: return ARCHIVE_FILTER_NONE\n case .gzip: return ARCHIVE_FILTER_GZIP\n case .bzip2: return ARCHIVE_FILTER_BZIP2\n case .compress: return ARCHIVE_FILTER_COMPRESS\n case .lzma: return ARCHIVE_FILTER_LZMA\n case .xz: return ARCHIVE_FILTER_XZ\n case .uu: return ARCHIVE_FILTER_UU\n case .rpm: return ARCHIVE_FILTER_RPM\n case .lzip: return ARCHIVE_FILTER_LZIP\n case .lrzip: return ARCHIVE_FILTER_LRZIP\n case .lzop: return ARCHIVE_FILTER_LZOP\n case .grzip: return ARCHIVE_FILTER_GRZIP\n case .lz4: return ARCHIVE_FILTER_LZ4\n }\n }\n}\n"], ["/containerization/Sources/Containerization/Image/ImageStore/ImageStore+Import.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\nextension ImageStore {\n internal struct ImportOperation {\n static let decoder = JSONDecoder()\n\n let client: ContentClient\n let ingestDir: URL\n let contentStore: ContentStore\n let progress: ProgressHandler?\n let name: String\n\n init(name: String, contentStore: ContentStore, client: ContentClient, ingestDir: URL, progress: ProgressHandler? = nil) {\n self.client = client\n self.ingestDir = ingestDir\n self.contentStore = contentStore\n self.progress = progress\n self.name = name\n }\n\n /// Pull the required image layers for the provided descriptor and platform(s) into the given directory using the provided client. Returns a descriptor to the Index manifest.\n internal func `import`(root: Descriptor, matcher: (ContainerizationOCI.Platform) -> Bool) async throws -> Descriptor {\n var toProcess = [root]\n while !toProcess.isEmpty {\n // Count the total number of blobs and their size\n if let progress {\n var size: Int64 = 0\n for desc in toProcess {\n size += desc.size\n }\n await progress([\n ProgressEvent(event: \"add-total-size\", value: size),\n ProgressEvent(event: \"add-total-items\", value: toProcess.count),\n ])\n }\n\n try await self.fetchAll(toProcess)\n let children = try await self.walk(toProcess)\n let filtered = try filterPlatforms(matcher: matcher, children)\n toProcess = filtered.uniqued { $0.digest }\n }\n\n guard root.mediaType != MediaTypes.dockerManifestList && root.mediaType != MediaTypes.index else {\n return root\n }\n\n // Create an index for the root descriptor and write it to the content store\n let index = try await self.createIndex(for: root)\n // In cases where the root descriptor pointed to `MediaTypes.imageManifest`\n // Or `MediaTypes.dockerManifest`, it is required that we check the supported platform\n // matches the platforms we were asked to pull. This can be done only after we created\n // the Index.\n let supportedPlatforms = index.manifests.compactMap { $0.platform }\n guard supportedPlatforms.allSatisfy(matcher) else {\n throw ContainerizationError(.unsupported, message: \"Image \\(root.digest) does not support required platforms\")\n }\n let writer = try ContentWriter(for: self.ingestDir)\n let result = try writer.create(from: index)\n return Descriptor(\n mediaType: MediaTypes.index,\n digest: result.digest.digestString,\n size: Int64(result.size))\n }\n\n private func getManifestContent(descriptor: Descriptor) async throws -> T {\n do {\n if let content = try await self.contentStore.get(digest: descriptor.digest.trimmingDigestPrefix) {\n return try content.decode()\n }\n if let content = try? LocalContent(path: ingestDir.appending(path: descriptor.digest.trimmingDigestPrefix)) {\n return try content.decode()\n }\n return try await self.client.fetch(name: name, descriptor: descriptor)\n } catch {\n throw ContainerizationError(.internalError, message: \"Cannot fetch content with digest \\(descriptor.digest)\", cause: error)\n }\n }\n\n private func walk(_ descriptors: [Descriptor]) async throws -> [Descriptor] {\n var out: [Descriptor] = []\n for desc in descriptors {\n let mediaType = desc.mediaType\n switch mediaType {\n case MediaTypes.index, MediaTypes.dockerManifestList:\n let index: Index = try await self.getManifestContent(descriptor: desc)\n out.append(contentsOf: index.manifests)\n case MediaTypes.imageManifest, MediaTypes.dockerManifest:\n let manifest: Manifest = try await self.getManifestContent(descriptor: desc)\n out.append(manifest.config)\n out.append(contentsOf: manifest.layers)\n default:\n // TODO: Explicitly handle other content types\n continue\n }\n }\n return out\n }\n\n private func fetchAll(_ descriptors: [Descriptor]) async throws {\n try await withThrowingTaskGroup(of: Void.self) { group in\n var iterator = descriptors.makeIterator()\n for _ in 0..<8 {\n if let desc = iterator.next() {\n group.addTask {\n try await fetch(desc)\n }\n }\n }\n for try await _ in group {\n if let desc = iterator.next() {\n group.addTask {\n try await fetch(desc)\n }\n }\n }\n }\n }\n\n private func fetch(_ descriptor: Descriptor) async throws {\n if let found = try await self.contentStore.get(digest: descriptor.digest) {\n try FileManager.default.copyItem(at: found.path, to: ingestDir.appendingPathComponent(descriptor.digest.trimmingDigestPrefix))\n await progress?([\n // Count the size of the blob\n ProgressEvent(event: \"add-size\", value: descriptor.size),\n // Count the number of blobs\n ProgressEvent(event: \"add-items\", value: 1),\n ])\n return\n }\n\n if descriptor.size > 1.mib() {\n try await self.fetchBlob(descriptor)\n } else {\n try await self.fetchData(descriptor)\n }\n // Count the number of blobs\n await progress?([\n ProgressEvent(event: \"add-items\", value: 1)\n ])\n }\n\n private func fetchBlob(_ descriptor: Descriptor) async throws {\n let id = UUID().uuidString\n let fm = FileManager.default\n let tempFile = ingestDir.appendingPathComponent(id)\n let (_, digest) = try await client.fetchBlob(name: name, descriptor: descriptor, into: tempFile, progress: progress)\n guard digest.digestString == descriptor.digest else {\n throw ContainerizationError(.internalError, message: \"Digest mismatch expected \\(descriptor.digest), got \\(digest.digestString)\")\n }\n do {\n try fm.moveItem(at: tempFile, to: ingestDir.appendingPathComponent(digest.encoded))\n } catch let err as NSError {\n guard err.code == NSFileWriteFileExistsError else {\n throw err\n }\n try fm.removeItem(at: tempFile)\n }\n }\n\n @discardableResult\n private func fetchData(_ descriptor: Descriptor) async throws -> Data {\n let data = try await client.fetchData(name: name, descriptor: descriptor)\n let writer = try ContentWriter(for: ingestDir)\n let result = try writer.write(data)\n if let progress {\n let size = Int64(result.size)\n await progress([\n ProgressEvent(event: \"add-size\", value: size)\n ])\n }\n guard result.digest.digestString == descriptor.digest else {\n throw ContainerizationError(.internalError, message: \"Digest mismatch expected \\(descriptor.digest), got \\(result.digest.digestString)\")\n }\n return data\n }\n\n private func createIndex(for root: Descriptor) async throws -> Index {\n switch root.mediaType {\n case MediaTypes.index, MediaTypes.dockerManifestList:\n return try await self.getManifestContent(descriptor: root)\n case MediaTypes.imageManifest, MediaTypes.dockerManifest:\n let supportedPlatforms = try await getSupportedPlatforms(for: root)\n guard supportedPlatforms.count == 1 else {\n throw ContainerizationError(\n .internalError,\n message:\n \"Descriptor \\(root.mediaType) with digest \\(root.digest) does not list any supported platform or supports more than one platform. Supported platforms = \\(supportedPlatforms)\"\n )\n }\n let platform = supportedPlatforms.first!\n var root = root\n root.platform = platform\n let index = ContainerizationOCI.Index(\n schemaVersion: 2, manifests: [root],\n annotations: [\n // indicate that this is a synthesized index which is not directly user facing\n AnnotationKeys.containerizationIndexIndirect: \"true\"\n ])\n return index\n default:\n throw ContainerizationError(.internalError, message: \"Failed to create index for descriptor \\(root.digest), media type \\(root.mediaType)\")\n }\n }\n\n private func getSupportedPlatforms(for root: Descriptor) async throws -> [ContainerizationOCI.Platform] {\n var supportedPlatforms: [ContainerizationOCI.Platform] = []\n var toProcess = [root]\n while !toProcess.isEmpty {\n let children = try await self.walk(toProcess)\n for child in children {\n if let p = child.platform {\n supportedPlatforms.append(p)\n continue\n }\n switch child.mediaType {\n case MediaTypes.imageConfig, MediaTypes.dockerImageConfig:\n let config: ContainerizationOCI.Image = try await self.getManifestContent(descriptor: child)\n let p = ContainerizationOCI.Platform(\n arch: config.architecture, os: config.os, osFeatures: config.osFeatures, variant: config.variant\n )\n supportedPlatforms.append(p)\n default:\n continue\n }\n }\n toProcess = children\n }\n return supportedPlatforms\n }\n\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/ArchiveWriter.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CArchive\nimport Foundation\n\n/// A class responsible for writing archives in various formats.\npublic final class ArchiveWriter {\n var underlying: OpaquePointer!\n var delegate: FileArchiveWriterDelegate?\n\n /// Initialize a new `ArchiveWriter` with the given configuration.\n /// This method attempts to initialize an empty archive in memory, failing which it throws a `unableToCreateArchive` error.\n public init(configuration: ArchiveWriterConfiguration) throws {\n // because for some bizarre reason, UTF8 paths won't work unless this process explicitly sets a locale like en_US.UTF-8\n try Self.attemptSetLocales(locales: configuration.locales)\n\n guard let underlying = archive_write_new() else { throw ArchiveError.unableToCreateArchive }\n self.underlying = underlying\n\n try setFormat(configuration.format)\n try addFilter(configuration.filter)\n try setOptions(configuration.options)\n }\n\n /// Initialize a new `ArchiveWriter` with the given configuration and specified delegate.\n private convenience init(configuration: ArchiveWriterConfiguration, delegate: FileArchiveWriterDelegate) throws {\n try self.init(configuration: configuration)\n self.delegate = delegate\n try self.open()\n }\n\n private convenience init(configuration: ArchiveWriterConfiguration, file: URL) throws {\n try self.init(configuration: configuration, delegate: FileArchiveWriterDelegate(url: file))\n }\n\n /// Initialize a new `ArchiveWriter` for writing into the specified file with the given configuration options.\n public convenience init(format: Format, filter: Filter, options: [Options] = [], file: URL) throws {\n try self.init(\n configuration: .init(format: format, filter: filter), delegate: FileArchiveWriterDelegate(url: file))\n }\n\n /// Opens the given file for writing data into\n public func open(file: URL) throws {\n guard let underlying = underlying else { throw ArchiveError.noUnderlyingArchive }\n let res = archive_write_open_filename(underlying, file.path)\n try wrap(res, ArchiveError.unableToOpenArchive, underlying: underlying)\n }\n\n /// Opens the given fd for writing data into\n public func open(fileDescriptor: Int32) throws {\n guard let underlying = underlying else { throw ArchiveError.noUnderlyingArchive }\n let res = archive_write_open_fd(underlying, fileDescriptor)\n try wrap(res, ArchiveError.unableToOpenArchive, underlying: underlying)\n }\n\n /// Performs any necessary finalizations on the archive and releases resources.\n public func finishEncoding() throws {\n if let u = underlying {\n let r = archive_free(u)\n do {\n try wrap(r, ArchiveError.unableToCloseArchive, underlying: underlying)\n underlying = nil\n } catch {\n underlying = nil\n throw error\n }\n }\n }\n\n deinit {\n if let u = underlying {\n archive_free(u)\n underlying = nil\n }\n }\n\n private static func attemptSetLocales(locales: [String]) throws {\n for locale in locales {\n if setlocale(LC_ALL, locale) != nil {\n return\n }\n }\n throw ArchiveError.failedToSetLocale(locales: locales)\n }\n}\n\nextension ArchiveWriter {\n fileprivate func open() throws {\n guard let underlying = underlying else { throw ArchiveError.noUnderlyingArchive }\n // TODO: to be or not to be retained, that is the question\n let pointerToSelf = Unmanaged.passUnretained(self).toOpaque()\n\n let res = archive_write_open2(\n underlying,\n pointerToSelf,\n /// The open callback is invoked by archive_write_open(). It should return ARCHIVE_OK if the underlying file or data source is successfully opened. If the open fails, it should call archive_set_error() to register an error code and message and return ARCHIVE_FATAL. Please note that\n /// if open fails, close is not called and resources must be freed inside the open callback or with the free callback.\n { underlying, pointerToSelf in\n do {\n guard let pointerToSelf = pointerToSelf else {\n throw ArchiveError.noArchiveInCallback\n }\n let archive: ArchiveWriter = Unmanaged.fromOpaque(pointerToSelf).takeUnretainedValue()\n guard let delegate = archive.delegate else {\n throw ArchiveError.noDelegateConfigured\n }\n try delegate.open(archive: archive)\n return ARCHIVE_OK\n } catch {\n archive_set_error_wrapper(underlying, ARCHIVE_FATAL, \"\\(error)\")\n return ARCHIVE_FATAL\n }\n },\n /// The write callback is invoked whenever the library needs to write raw bytes to the archive. For correct blocking, each call to the write callback function should translate into a single write(2) system call. This is especially critical when writing archives to tape drives. On\n /// success, the write callback should return the number of bytes actually written. On error, the callback should invoke archive_set_error() to register an error code and message and return -1.\n { underlying, pointerToSelf, dataPointer, count in\n do {\n guard let pointerToSelf = pointerToSelf else {\n throw ArchiveError.noArchiveInCallback\n }\n let archive: ArchiveWriter = Unmanaged.fromOpaque(pointerToSelf).takeUnretainedValue()\n guard let delegate = archive.delegate else {\n throw ArchiveError.noDelegateConfigured\n }\n return try delegate.write(\n archive: archive, buffer: UnsafeRawBufferPointer(start: dataPointer, count: count))\n } catch {\n archive_set_error_wrapper(underlying, ARCHIVE_FATAL, \"\\(error)\")\n return -1\n }\n },\n /// The close callback is invoked by archive_close when the archive processing is complete. If the open callback fails, the close callback is not invoked. The callback should return ARCHIVE_OK on success. On failure, the callback should invoke archive_set_error() to register an\n /// error code and message and return\n { underlying, pointerToSelf in\n do {\n guard let pointerToSelf = pointerToSelf else {\n throw ArchiveError.noArchiveInCallback\n }\n let archive: ArchiveWriter = Unmanaged.fromOpaque(pointerToSelf).takeUnretainedValue()\n guard let delegate = archive.delegate else {\n throw ArchiveError.noDelegateConfigured\n }\n try delegate.close(archive: archive)\n return ARCHIVE_OK\n } catch {\n archive_set_error_wrapper(underlying, ARCHIVE_FATAL, \"\\(error)\")\n return ARCHIVE_FATAL\n }\n },\n /// The free callback is always invoked on archive_free. The return code of this callback is not processed.\n { underlying, pointerToSelf in\n do {\n guard let pointerToSelf = pointerToSelf else {\n throw ArchiveError.noArchiveInCallback\n }\n let archive: ArchiveWriter = Unmanaged.fromOpaque(pointerToSelf).takeUnretainedValue()\n guard let delegate = archive.delegate else {\n throw ArchiveError.noDelegateConfigured\n }\n delegate.free(archive: archive)\n\n // TODO: should we balance the Unmanaged refcount here? Need to test for leaks.\n return ARCHIVE_OK\n } catch {\n archive_set_error_wrapper(underlying, ARCHIVE_FATAL, \"\\(error)\")\n return ARCHIVE_FATAL\n }\n }\n )\n\n try wrap(res, ArchiveError.unableToOpenArchive, underlying: underlying)\n }\n}\n\npublic class ArchiveWriterTransaction {\n private let writer: ArchiveWriter\n\n fileprivate init(writer: ArchiveWriter) {\n self.writer = writer\n }\n\n public func writeHeader(entry: WriteEntry) throws {\n try writer.writeHeader(entry: entry)\n }\n\n public func writeChunk(data: UnsafeRawBufferPointer) throws {\n try writer.writeData(data: data)\n }\n\n public func finish() throws {\n try writer.finishEntry()\n }\n}\n\nextension ArchiveWriter {\n public func makeTransactionWriter() -> ArchiveWriterTransaction {\n ArchiveWriterTransaction(writer: self)\n }\n\n /// Create a new entry in the archive with the given properties.\n /// - Parameters:\n /// - entry: A `WriteEntry` object describing the metadata of the entry to be created\n /// (e.g., name, modification date, permissions).\n /// - data: The `Data` object containing the content for the new entry.\n public func writeEntry(entry: WriteEntry, data: Data) throws {\n try data.withUnsafeBytes { bytes in\n try writeEntry(entry: entry, data: bytes)\n }\n }\n\n /// Creates a new entry in the archive with the given properties.\n ///\n /// This method performs the following:\n /// 1. Writes the archive header using the provided `WriteEntry` metadata.\n /// 2. Writes the content from the `UnsafeRawBufferPointer` into the archive.\n /// 3. Finalizes the entry in the archive.\n ///\n /// - Parameters:\n /// - entry: A `WriteEntry` object describing the metadata of the entry to be created\n /// (e.g., name, modification date, permissions, type).\n /// - data: An optional `UnsafeRawBufferPointer` containing the raw bytes for the new entry's\n /// content. Pass `nil` for entries that do not have content data (e.g., directories, symlinks).\n public func writeEntry(entry: WriteEntry, data: UnsafeRawBufferPointer?) throws {\n try writeHeader(entry: entry)\n if let data = data {\n try writeData(data: data)\n }\n try finishEntry()\n }\n\n fileprivate func writeHeader(entry: WriteEntry) throws {\n guard let underlying = self.underlying else { throw ArchiveError.noUnderlyingArchive }\n\n try wrap(\n archive_write_header(underlying, entry.underlying), ArchiveError.unableToWriteEntryHeader,\n underlying: underlying)\n }\n\n fileprivate func finishEntry() throws {\n guard let underlying = self.underlying else { throw ArchiveError.noUnderlyingArchive }\n\n archive_write_finish_entry(underlying)\n }\n\n fileprivate func writeData(data: UnsafeRawBufferPointer) throws {\n guard let underlying = self.underlying else { throw ArchiveError.noUnderlyingArchive }\n\n let result = archive_write_data(underlying, data.baseAddress, data.count)\n guard result >= 0 else {\n throw ArchiveError.unableToWriteData(result)\n }\n }\n}\n\nextension ArchiveWriter {\n /// Recursively archives the content of a directory. Regular files, symlinks and directories are added into the archive.\n /// Note: Symlinks are added to the archive if both the source and target for the symlink are both contained in the top level directory.\n public func archiveDirectory(_ dir: URL) throws {\n let fm = FileManager.default\n let resourceKeys = Set([\n .fileSizeKey, .fileResourceTypeKey,\n .creationDateKey, .contentAccessDateKey, .contentModificationDateKey, .fileSecurityKey,\n ])\n guard let directoryEnumerator = fm.enumerator(at: dir, includingPropertiesForKeys: Array(resourceKeys), options: .producesRelativePathURLs) else {\n throw POSIXError(.ENOTDIR)\n }\n for case let fileURL as URL in directoryEnumerator {\n var mode = mode_t()\n var uid = uid_t()\n var gid = gid_t()\n let resourceValues = try fileURL.resourceValues(forKeys: resourceKeys)\n guard let type = resourceValues.fileResourceType else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .fileResourceTypeKey)\n }\n let allowedTypes: [URLFileResourceType] = [.directory, .regular, .symbolicLink]\n guard allowedTypes.contains(type) else {\n continue\n }\n var size: Int64 = 0\n let entry = WriteEntry()\n if type == .regular {\n guard let _size = resourceValues.fileSize else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .fileSizeKey)\n }\n size = Int64(_size)\n } else if type == .symbolicLink {\n let target = fileURL.resolvingSymlinksInPath().absoluteString\n let root = dir.absoluteString\n guard target.hasPrefix(root) else {\n continue\n }\n let linkTarget = target.dropFirst(root.count + 1)\n entry.symlinkTarget = String(linkTarget)\n }\n\n guard let created = resourceValues.creationDate else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .creationDateKey)\n }\n guard let access = resourceValues.contentAccessDate else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .contentAccessDateKey)\n }\n guard let modified = resourceValues.contentModificationDate else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .contentModificationDateKey)\n }\n guard let perms = resourceValues.fileSecurity else {\n throw ArchiveError.failedToGetProperty(fileURL.path(), .fileSecurityKey)\n }\n CFFileSecurityGetMode(perms, &mode)\n CFFileSecurityGetOwner(perms, &uid)\n CFFileSecurityGetGroup(perms, &gid)\n entry.path = fileURL.relativePath\n entry.size = size\n entry.creationDate = created\n entry.modificationDate = modified\n entry.contentAccessDate = access\n entry.fileType = type\n entry.group = gid\n entry.owner = uid\n entry.permissions = mode\n if type == .regular {\n let p = dir.appending(path: fileURL.relativePath)\n let data = try Data(contentsOf: p, options: .uncached)\n try self.writeEntry(entry: entry, data: data)\n } else {\n try self.writeHeader(entry: entry)\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Reader.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\nextension EXT4 {\n /// The `EXT4Reader` opens a block device, parses the superblock, and loads group descriptors & inodes.\n public class EXT4Reader {\n public var superBlock: EXT4.SuperBlock {\n self._superBlock\n }\n\n let handle: FileHandle\n let _superBlock: EXT4.SuperBlock\n\n private var groupDescriptors: [UInt32: EXT4.GroupDescriptor] = [:]\n private var inodes: [InodeNumber: EXT4.Inode] = [:]\n\n var hardlinks: [FilePath: InodeNumber] = [:]\n var tree: EXT4.FileTree = EXT4.FileTree(EXT4.RootInode, \".\")\n var blockSize: UInt64 {\n UInt64(1024 * (1 << _superBlock.logBlockSize))\n }\n\n private var groupDescriptorSize: UInt16 {\n if _superBlock.featureIncompat & EXT4.IncompatFeature.bit64.rawValue != 0 {\n return _superBlock.descSize\n }\n return UInt16(MemoryLayout.size)\n }\n\n public init(blockDevice: FilePath) throws {\n guard FileManager.default.fileExists(atPath: blockDevice.description) else {\n throw EXT4.Error.notFound(blockDevice.description)\n }\n\n guard let fileHandle = FileHandle(forReadingAtPath: blockDevice) else {\n throw Error.notFound(blockDevice.description)\n }\n self.handle = fileHandle\n try handle.seek(toOffset: EXT4.SuperBlockOffset)\n\n let superBlockSize = MemoryLayout.size\n guard let data = try? self.handle.read(upToCount: superBlockSize) else {\n throw EXT4.Error.couldNotReadSuperBlock(blockDevice.description, EXT4.SuperBlockOffset, superBlockSize)\n }\n let sb = data.withUnsafeBytes { ptr in\n ptr.loadLittleEndian(as: EXT4.SuperBlock.self)\n }\n guard sb.magic == EXT4.SuperBlockMagic else {\n throw EXT4.Error.invalidSuperBlock\n }\n self._superBlock = sb\n var items: [(item: Ptr, inode: InodeNumber)] = [\n (self.tree.root, EXT4.RootInode)\n ]\n while items.count > 0 {\n guard let item = items.popLast() else {\n break\n }\n let (itemPtr, inodeNum) = item\n let childItems = try self.children(of: inodeNum)\n let root = itemPtr.pointee\n for (itemName, itemInodeNum) in childItems {\n if itemName == \".\" || itemName == \"..\" {\n continue\n }\n\n if self.inodes[itemInodeNum] != nil {\n // we have seen this inode before, we will hard link this file to it\n guard let parentPath = itemPtr.pointee.path else {\n continue\n }\n let path = parentPath.join(itemName)\n self.hardlinks[path] = itemInodeNum\n continue\n }\n\n let blocks = try self.getExtents(inode: itemInodeNum)\n let itemTreeNodePtr = Ptr.allocate(capacity: 1)\n let itemTreeNode = FileTree.FileTreeNode(\n inode: itemInodeNum,\n name: itemName,\n parent: itemPtr,\n children: []\n )\n if let blocks {\n if blocks.count > 1 {\n itemTreeNode.additionalBlocks = Array(blocks.dropFirst())\n }\n itemTreeNode.blocks = blocks.first\n }\n itemTreeNodePtr.initialize(to: itemTreeNode)\n root.children.append(itemTreeNodePtr)\n itemPtr.initialize(to: root)\n let itemInode = try self.getInode(number: itemInodeNum)\n if itemInode.mode.isDir() {\n items.append((itemTreeNodePtr, itemInodeNum))\n }\n }\n }\n }\n\n deinit {\n try? self.handle.close()\n }\n\n private func readGroupDescriptor(_ number: UInt32) throws -> GroupDescriptor {\n let bs = UInt64(1024 * (1 << _superBlock.logBlockSize))\n let offset = bs + UInt64(number) * UInt64(self.groupDescriptorSize)\n try self.handle.seek(toOffset: offset)\n guard let data = try? self.handle.read(upToCount: MemoryLayout.size) else {\n throw EXT4.Error.couldNotReadGroup(number)\n }\n let gd = data.withUnsafeBytes { ptr in\n ptr.loadLittleEndian(as: EXT4.GroupDescriptor.self)\n }\n return gd\n }\n\n private func readInode(_ number: UInt32) throws -> Inode {\n let inodeGroupNumber = ((number - 1) / self._superBlock.inodesPerGroup)\n let numberInGroup = UInt64((number - 1) % self._superBlock.inodesPerGroup)\n\n let gd = try getGroupDescriptor(inodeGroupNumber)\n let inodeTableStart = UInt64(gd.inodeTableLow) * self.blockSize\n\n let inodeOffset: UInt64 = inodeTableStart + numberInGroup * UInt64(_superBlock.inodeSize)\n try self.handle.seek(toOffset: inodeOffset)\n guard let inodeData = try self.handle.read(upToCount: MemoryLayout.size) else {\n throw EXT4.Error.couldNotReadInode(number)\n }\n let inode = inodeData.withUnsafeBytes { ptr in\n ptr.loadLittleEndian(as: EXT4.Inode.self)\n }\n return inode\n }\n\n private func getDirTree(_ number: InodeNumber) throws -> [(String, InodeNumber)] {\n var children: [(String, InodeNumber)] = []\n let extents = try getExtents(inode: number) ?? []\n for (start, end) in extents {\n try self.seek(block: start)\n for i in 0..<(end - start) {\n guard let dirEntryBlock = try self.handle.read(upToCount: Int(self.blockSize)) else {\n throw EXT4.Error.couldNotReadBlock(start + i)\n }\n let childEntries = try getDirEntries(dirTree: dirEntryBlock)\n children.append(contentsOf: childEntries)\n }\n }\n return children.sorted { a, b in\n a.0 < b.0\n }\n }\n\n private func getDirEntries(dirTree: Data) throws -> [(String, InodeNumber)] {\n var children: [(String, InodeNumber)] = []\n var offset = 0\n while offset < dirTree.count {\n let length = MemoryLayout.size\n let dirEntry = dirTree.subdata(in: offset.. [(start: UInt32, end: UInt32)]? {\n let inode = try self.getInode(number: inode)\n let inodeBlock = Data(tupleToArray(inode.block))\n var offset = 0\n var extents: [(start: UInt32, end: UInt32)] = []\n\n let extentHeaderSize = MemoryLayout.size\n let extentIndexSize = MemoryLayout.size\n let extentLeafSize = MemoryLayout.size\n // read extent header\n let header = inodeBlock.subdata(in: offset.. Inode {\n if let inode = self.inodes[number] {\n return inode\n }\n\n let inode = try readInode(number)\n self.inodes[number] = inode\n return inode\n }\n\n func getGroupDescriptor(_ number: UInt32) throws -> GroupDescriptor {\n if let gd = self.groupDescriptors[number] {\n return gd\n }\n let gd = try readGroupDescriptor(number)\n self.groupDescriptors[number] = gd\n return gd\n }\n\n func children(of number: EXT4.InodeNumber) throws -> [(String, InodeNumber)] {\n try getDirTree(number)\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/KeychainHelper.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\nimport ContainerizationOS\n\n/// Helper type to lookup registry related values in the macOS keychain.\npublic struct KeychainHelper: Sendable {\n private let id: String\n public init(id: String) {\n self.id = id\n }\n\n /// Lookup authorization data for a given registry domain.\n public func lookup(domain: String) throws -> Authentication {\n let kq = KeychainQuery()\n\n do {\n guard let fetched = try kq.get(id: self.id, host: domain) else {\n throw Self.Error.keyNotFound\n }\n return BasicAuthentication(\n username: fetched.account,\n password: fetched.data\n )\n } catch let err as KeychainQuery.Error {\n switch err {\n case .keyNotPresent(_):\n throw Self.Error.keyNotFound\n default:\n throw Self.Error.queryError(\"query failure: \\(String(describing: err))\")\n }\n }\n }\n\n /// Delete authorization data for a given domain from the keychain.\n public func delete(domain: String) throws {\n let kq = KeychainQuery()\n try kq.delete(id: self.id, host: domain)\n }\n\n /// Save authorization data for a given domain to the keychain.\n public func save(domain: String, username: String, password: String) throws {\n let kq = KeychainQuery()\n try kq.save(id: self.id, host: domain, user: username, token: password)\n }\n\n /// Prompt for authorization data for a given domain to be saved to the keychain.\n /// This will cause the current terminal to enter a password prompt state where\n /// key strokes are hidden.\n public func credentialPrompt(domain: String) throws -> Authentication {\n let username = try userPrompt(domain: domain)\n let password = try passwordPrompt()\n return BasicAuthentication(username: username, password: password)\n }\n\n /// Prompts the current stdin for a username entry and then returns the value.\n public func userPrompt(domain: String) throws -> String {\n print(\"Provide registry username \\(domain): \", terminator: \"\")\n guard let username = readLine() else {\n throw Self.Error.invalidInput\n }\n return username\n }\n\n /// Prompts the current stdin for a password entry and then returns the value.\n /// This will cause the current stdin (if it is a terminal) to hide keystrokes\n /// by disabling echo.\n public func passwordPrompt() throws -> String {\n print(\"Provide registry password: \", terminator: \"\")\n let console = try Terminal.current\n defer { console.tryReset() }\n try console.disableEcho()\n\n guard let password = readLine() else {\n throw Self.Error.invalidInput\n }\n return password\n }\n}\n\nextension KeychainHelper {\n /// `KeychainHelper` errors.\n public enum Error: Swift.Error {\n case keyNotFound\n case invalidInput\n case queryError(String)\n }\n}\n#endif\n"], ["/containerization/Sources/Containerization/Image/InitImage.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\n/// Data representing the image to use as the root filesystem for a virtual machine.\n/// Typically this image would contain the guest agent used to facilitate container\n/// workloads, as well as any extras that may be useful to have in the guest.\npublic struct InitImage: Sendable {\n public var name: String { image.reference }\n\n let image: Image\n\n public init(image: Image) {\n self.image = image\n }\n}\n\nextension InitImage {\n /// Unpack the initial filesystem for the desired platform at a given path.\n public func initBlock(at: URL, for platform: SystemPlatform) async throws -> Mount {\n let unpacker = EXT4Unpacker(blockSizeInBytes: 512.mib())\n var fs = try await unpacker.unpack(self.image, for: platform.ociPlatform(), at: at)\n fs.options = [\"ro\"]\n return fs\n }\n\n /// Create a new InitImage with the reference as the name.\n /// The `rootfs` parameter must be a tar.gz file whose contents make up the filesystem for the image.\n public static func create(\n reference: String, rootfs: URL, platform: Platform,\n labels: [String: String] = [:], imageStore: ImageStore, contentStore: ContentStore\n ) async throws -> InitImage {\n\n let indexDescriptorStore = AsyncStore()\n try await contentStore.ingest { dir in\n let writer = try ContentWriter(for: dir)\n var result = try writer.create(from: rootfs)\n let layerDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.imageLayerGzip, digest: result.digest.digestString, size: result.size)\n\n // TODO: compute and fill in the correct diffID for the above layer\n // We currently put in the sha of the fully compressed layer, this needs to be replaced with\n // the sha of the uncompressed layer.\n let rootfsConfig = ContainerizationOCI.Rootfs(type: \"layers\", diffIDs: [result.digest.digestString])\n let runtimeConfig = ContainerizationOCI.ImageConfig(labels: labels)\n let imageConfig = ContainerizationOCI.Image(architecture: platform.architecture, os: platform.os, config: runtimeConfig, rootfs: rootfsConfig)\n result = try writer.create(from: imageConfig)\n let configDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.imageConfig, digest: result.digest.digestString, size: result.size)\n\n let manifest = Manifest(config: configDescriptor, layers: [layerDescriptor])\n result = try writer.create(from: manifest)\n let manifestDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.imageManifest, digest: result.digest.digestString, size: result.size, platform: platform)\n\n let index = ContainerizationOCI.Index(manifests: [manifestDescriptor])\n result = try writer.create(from: index)\n\n let indexDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.index, digest: result.digest.digestString, size: result.size)\n await indexDescriptorStore.set(indexDescriptor)\n\n }\n\n guard let indexDescriptor = await indexDescriptorStore.get() else {\n throw ContainerizationError(.notFound, message: \"image for \\(reference) not found\")\n }\n\n let description = Image.Description(reference: reference, descriptor: indexDescriptor)\n let image = try await imageStore.create(description: description)\n return InitImage(image: image)\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/RegistryClient+Token.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport ContainerizationError\nimport Foundation\n\nstruct TokenRequest {\n public static let authenticateHeaderName = \"WWW-Authenticate\"\n\n /// The credentials that will be used in the authentication header when fetching the token.\n let authentication: Authentication?\n /// The realm against which the token should be requested.\n let realm: String\n /// The name of the service which hosts the resource.\n let service: String\n /// Whether to return a refresh token along with the bearer token.\n let offlineToken: Bool\n /// String identifying the client.\n let clientId: String\n /// The resource in question, formatted as one of the space-delimited entries from the scope parameters from the WWW-Authenticate header shown above.\n let scope: String?\n\n init(\n realm: String,\n service: String,\n clientId: String,\n scope: String?,\n offlineToken: Bool = false,\n authentication: Authentication? = nil\n ) {\n self.realm = realm\n self.service = service\n self.offlineToken = offlineToken\n self.clientId = clientId\n self.scope = scope\n self.authentication = authentication\n }\n}\n\nstruct TokenResponse: Codable, Hashable {\n /// An opaque Bearer token that clients should supply to subsequent requests in the Authorization header.\n let token: String?\n /// For compatibility with OAuth 2.0, we will also accept token under the name access_token.\n /// At least one of these fields must be specified, but both may also appear (for compatibility with older clients).\n /// When both are specified, they should be equivalent; if they differ the client's choice is undefined.\n let accessToken: String?\n /// The duration in seconds since the token was issued that it will remain valid.\n /// When omitted, this defaults to 60 seconds.\n let expiresIn: UInt?\n /// The RFC3339-serialized UTC standard time at which a given token was issued.\n /// If issued_at is omitted, the expiration is from when the token exchange completed.\n let issuedAt: String?\n /// Token which can be used to get additional access tokens for the same subject with different scopes.\n /// This token should be kept secure by the client and only sent to the authorization server which issues bearer tokens.\n /// This field will only be set when `offline_token=true` is provided in the request.\n let refreshToken: String?\n\n var scope: String?\n\n private enum CodingKeys: String, CodingKey {\n case token = \"token\"\n case accessToken = \"access_token\"\n case expiresIn = \"expires_in\"\n case issuedAt = \"issued_at\"\n case refreshToken = \"refresh_token\"\n }\n\n func getToken() -> String? {\n if let t = token ?? accessToken {\n return \"Bearer \\(t)\"\n }\n return nil\n }\n\n func isValid(scope: String?) -> Bool {\n guard let issuedAt else {\n return false\n }\n let isoFormatter = ISO8601DateFormatter()\n isoFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]\n guard let issued = isoFormatter.date(from: issuedAt) else {\n return false\n }\n let expiresIn = expiresIn ?? 0\n let now = Date()\n let elapsed = now.timeIntervalSince(issued)\n guard elapsed < Double(expiresIn) else {\n return false\n }\n if let requiredScope = scope {\n return requiredScope == self.scope\n }\n return false\n }\n}\n\nstruct AuthenticateChallenge: Equatable {\n let type: String\n let realm: String?\n let service: String?\n let scope: String?\n let error: String?\n\n init(type: String, realm: String?, service: String?, scope: String?, error: String?) {\n self.type = type\n self.realm = realm\n self.service = service\n self.scope = scope\n self.error = error\n }\n\n init(type: String, values: [String: String]) {\n self.type = type\n self.realm = values[\"realm\"]\n self.service = values[\"service\"]\n self.scope = values[\"scope\"]\n self.error = values[\"error\"]\n }\n}\n\nextension RegistryClient {\n /// Fetch an auto token for all subsequent HTTP requests\n /// See https://docs.docker.com/registry/spec/auth/token/\n internal func fetchToken(request: TokenRequest) async throws -> TokenResponse {\n guard var components = URLComponents(string: request.realm) else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot create URL from \\(request.realm)\")\n }\n components.queryItems = [\n URLQueryItem(name: \"client_id\", value: request.clientId),\n URLQueryItem(name: \"service\", value: request.service),\n ]\n var scope = \"\"\n if let reqScope = request.scope {\n scope = reqScope\n components.queryItems?.append(URLQueryItem(name: \"scope\", value: reqScope))\n }\n\n if request.offlineToken {\n components.queryItems?.append(URLQueryItem(name: \"offline_token\", value: \"true\"))\n }\n var response: TokenResponse = try await requestJSON(components: components, headers: [])\n response.scope = scope\n return response\n }\n\n internal func createTokenRequest(parsing authenticateHeaders: [String]) throws -> TokenRequest {\n let parsedHeaders = Self.parseWWWAuthenticateHeaders(headers: authenticateHeaders)\n let bearerChallenge = parsedHeaders.first { $0.type == \"Bearer\" }\n guard let bearerChallenge else {\n throw ContainerizationError(.invalidArgument, message: \"Missing Bearer challenge in \\(TokenRequest.authenticateHeaderName) header\")\n }\n guard let realm = bearerChallenge.realm else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot parse realm from \\(TokenRequest.authenticateHeaderName) header\")\n }\n guard let service = bearerChallenge.service else {\n throw ContainerizationError(.invalidArgument, message: \"Cannot parse service from \\(TokenRequest.authenticateHeaderName) header\")\n }\n let scope = bearerChallenge.scope\n let tokenRequest = TokenRequest(realm: realm, service: service, clientId: self.clientID, scope: scope, authentication: self.authentication)\n return tokenRequest\n }\n\n internal static func parseWWWAuthenticateHeaders(headers: [String]) -> [AuthenticateChallenge] {\n var parsed: [String: [String: String]] = [:]\n for challenge in headers {\n let trimmedChallenge = challenge.trimmingCharacters(in: .whitespacesAndNewlines)\n let parts = trimmedChallenge.split(separator: \" \", maxSplits: 1)\n guard parts.count == 2 else {\n continue\n }\n guard let scheme = parts.first else {\n continue\n }\n var params: [String: String] = [:]\n let header = String(parts[1])\n let pattern = #\"(\\w+)=\"([^\"]+)\"#\n let regex = try! NSRegularExpression(pattern: pattern, options: [])\n let matches = regex.matches(in: header, options: [], range: NSRange(header.startIndex..., in: header))\n for match in matches {\n if let keyRange = Range(match.range(at: 1), in: header),\n let valueRange = Range(match.range(at: 2), in: header)\n {\n let key = String(header[keyRange])\n let value = String(header[valueRange])\n params[key] = value\n }\n }\n parsed[String(scheme)] = params\n }\n var parsedChallenges: [AuthenticateChallenge] = []\n for (type, values) in parsed {\n parsedChallenges.append(.init(type: type, values: values))\n }\n return parsedChallenges\n }\n}\n"], ["/containerization/Sources/Containerization/Image/Unpacker/EXT4Unpacker.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\n#if os(macOS)\nimport ContainerizationArchive\nimport ContainerizationEXT4\nimport SystemPackage\n#endif\n\npublic struct EXT4Unpacker: Unpacker {\n let blockSizeInBytes: UInt64\n\n public init(blockSizeInBytes: UInt64) {\n self.blockSizeInBytes = blockSizeInBytes\n }\n\n public func unpack(_ image: Image, for platform: Platform, at path: URL, progress: ProgressHandler? = nil) async throws -> Mount {\n #if !os(macOS)\n throw ContainerizationError(.unsupported, message: \"Cannot unpack an image on current platform\")\n #else\n let blockPath = try prepareUnpackPath(path: path)\n let manifest = try await image.manifest(for: platform)\n let filesystem = try EXT4.Formatter(FilePath(path), minDiskSize: blockSizeInBytes)\n defer { try? filesystem.close() }\n\n for layer in manifest.layers {\n try Task.checkCancellation()\n let content = try await image.getContent(digest: layer.digest)\n\n let compression: ContainerizationArchive.Filter\n switch layer.mediaType {\n case MediaTypes.imageLayer, MediaTypes.dockerImageLayer:\n compression = .none\n case MediaTypes.imageLayerGzip, MediaTypes.dockerImageLayerGzip:\n compression = .gzip\n default:\n throw ContainerizationError(.unsupported, message: \"Media type \\(layer.mediaType) not supported.\")\n }\n try filesystem.unpack(\n source: content.path,\n format: .paxRestricted,\n compression: compression,\n progress: progress\n )\n }\n\n return .block(\n format: \"ext4\",\n source: blockPath,\n destination: \"/\",\n options: []\n )\n #endif\n }\n\n private func prepareUnpackPath(path: URL) throws -> String {\n let blockPath = path.absolutePath()\n guard !FileManager.default.fileExists(atPath: blockPath) else {\n throw ContainerizationError(.exists, message: \"block device already exists at \\(blockPath)\")\n }\n return blockPath\n }\n}\n"], ["/containerization/Sources/Containerization/Image/KernelImage.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\n/// A multi-arch kernel image represented by an OCI image.\npublic struct KernelImage: Sendable {\n /// The media type for a kernel image.\n public static let mediaType = \"application/vnd.apple.containerization.kernel\"\n\n /// The name or reference of the image.\n public var name: String { image.reference }\n\n let image: Image\n\n public init(image: Image) {\n self.image = image\n }\n}\n\nextension KernelImage {\n /// Return the kernel from a multi arch image for a specific system platform.\n public func kernel(for platform: SystemPlatform) async throws -> Kernel {\n let manifest = try await image.manifest(for: platform.ociPlatform())\n guard let descriptor = manifest.layers.first, descriptor.mediaType == Self.mediaType else {\n throw ContainerizationError(.notFound, message: \"kernel descriptor for \\(platform) not found\")\n }\n let content = try await image.getContent(digest: descriptor.digest)\n return Kernel(\n path: content.path,\n platform: platform\n )\n }\n\n /// Create a new kernel image with the reference as the name.\n /// This will create a multi arch image containing kernel's for each provided architecture.\n public static func create(reference: String, binaries: [Kernel], labels: [String: String] = [:], imageStore: ImageStore, contentStore: ContentStore) async throws -> KernelImage\n {\n let indexDescriptorStore = AsyncStore()\n try await contentStore.ingest { ingestPath in\n var descriptors = [Descriptor]()\n let writer = try ContentWriter(for: ingestPath)\n\n for kernel in binaries {\n var result = try writer.create(from: kernel.path)\n let platform = kernel.platform.ociPlatform()\n let layerDescriptor = Descriptor(\n mediaType: mediaType,\n digest: result.digest.digestString,\n size: result.size,\n platform: platform)\n let rootfsConfig = ContainerizationOCI.Rootfs(type: \"layers\", diffIDs: [result.digest.digestString])\n let runtimeConfig = ContainerizationOCI.ImageConfig(labels: labels)\n let imageConfig = ContainerizationOCI.Image(architecture: platform.architecture, os: platform.os, config: runtimeConfig, rootfs: rootfsConfig)\n\n result = try writer.create(from: imageConfig)\n let configDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.imageConfig, digest: result.digest.digestString, size: result.size)\n\n let manifest = Manifest(config: configDescriptor, layers: [layerDescriptor])\n result = try writer.create(from: manifest)\n let manifestDescriptor = Descriptor(\n mediaType: ContainerizationOCI.MediaTypes.imageManifest, digest: result.digest.digestString, size: result.size, platform: platform)\n descriptors.append(manifestDescriptor)\n }\n let index = ContainerizationOCI.Index(manifests: descriptors)\n let result = try writer.create(from: index)\n let indexDescriptor = Descriptor(mediaType: ContainerizationOCI.MediaTypes.index, digest: result.digest.digestString, size: result.size)\n await indexDescriptorStore.set(indexDescriptor)\n }\n\n guard let indexDescriptor = await indexDescriptorStore.get() else {\n throw ContainerizationError(.notFound, message: \"image for \\(reference) not found\")\n }\n\n let description = Image.Description(reference: reference, descriptor: indexDescriptor)\n let image = try await imageStore.create(description: description)\n return KernelImage(image: image)\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Formatter.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// swiftlint: disable discouraged_direct_init shorthand_operator syntactic_sugar\n\nimport ContainerizationOS\nimport Foundation\nimport SystemPackage\n\nextension EXT4 {\n /// The `EXT4.Formatter` class provides methods to format a block device with the ext4 filesystem.\n /// It allows customization of block size and maximum disk size.\n public class Formatter {\n private let blockSize: UInt32\n private var size: UInt64\n private let groupDescriptorSize: UInt32 = 32\n\n private var blocksPerGroup: UInt32 {\n blockSize * 8\n }\n\n private var maxInodesPerGroup: UInt32 {\n blockSize * 8 // limited by inode bitmap\n }\n\n private var groupsPerDescriptorBlock: UInt32 {\n blockSize / groupDescriptorSize\n }\n\n private var blockCount: UInt32 {\n ((size - 1) / blockSize) + 1\n }\n\n private var groupCount: UInt32 {\n (blockCount - 1) / blocksPerGroup + 1\n }\n\n private var groupDescriptorBlocks: UInt32 {\n ((groupCount - 1) / groupsPerDescriptorBlock + 1) * 32\n }\n\n /// Initializes an ext4 filesystem formatter.\n ///\n /// This constructor creates an instance of the ext4 formatter designed to format a block device\n /// with the ext4 filesystem. The formatter takes the path to the destination block device and\n /// the desired block size of the filesystem as parameters.\n ///\n /// - Parameters:\n /// - devicePath: The path to the block device where the ext4 filesystem will be created.\n /// - blockSize: The block size of the ext4 filesystem, specified in bytes. Common values are\n /// 4096 (4KB) or 1024 (1KB). Default is 4096 (4KB)\n /// - minDiskSize: The minimum disk size required for the formatted filesystem.\n ///\n /// - Note: This ext4 formatter is designed for creating block devices out of container images and does not support all the\n /// features and options available in the full ext4 filesystem implementation. It focuses\n /// on the core functionality required for formatting a block device with ext4.\n ///\n /// - Important: Ensure that the destination block device is accessible and has sufficient permissions\n /// for formatting. The formatting process will erase all existing data on the device.\n public init(_ devicePath: FilePath, blockSize: UInt32 = 4096, minDiskSize: UInt64 = 256.kib()) throws {\n /// The constructor performs the following steps:\n ///\n /// 1. Creates the first 10 inodes:\n /// - Inode 2 is reserved for the root directory ('/').\n /// - Inodes 1 and 3-10 are reserved for other special purposes.\n ///\n /// 2. Marks inode 11 as the first inode available for consumption by files, directories, sockets,\n /// FIFOs, etc.\n ///\n /// 3. Initializes a directory tree with the root directory pointing to inode 2.\n ///\n /// 4. Moves the file descriptor to the start of the block where file metadata and data can be\n /// written, which is located past the filesystem superblocks and group descriptor blocks.\n ///\n /// 5. Creates a \"/lost+found\" directory to satisfy the requirements of e2fsck (ext2/3/4 filesystem\n /// checker).\n\n if !FileManager.default.fileExists(atPath: devicePath.description) {\n FileManager.default.createFile(atPath: devicePath.description, contents: nil)\n }\n guard let fileHandle = FileHandle(forWritingTo: devicePath) else {\n throw Error.notFound(devicePath)\n }\n self.handle = fileHandle\n self.blockSize = blockSize\n self.size = minDiskSize\n // make this a 0 byte file\n guard ftruncate(self.handle.fileDescriptor, 0) == 0 else {\n throw Error.cannotTruncateFile(devicePath)\n }\n // make it a sparse file\n guard lseek(self.handle.fileDescriptor, off_t(self.size - 1), 0) == self.size - 1 else {\n throw Error.cannotCreateSparseFile(devicePath)\n }\n let zero: [UInt8] = [0]\n try self.handle.write(contentsOf: zero)\n // step #1\n self.inodes = [\n Ptr.allocate(capacity: 1), // defective block inode\n {\n let root = Inode.Root()\n let rootPtr = Ptr.allocate(capacity: 1)\n rootPtr.initialize(to: root)\n return rootPtr\n }(),\n ]\n // reserved inodes\n for _ in 2...allocate(capacity: 1))\n }\n // step #2\n self.tree = FileTree(EXT4.RootInode, \"/\")\n // skip past the superblock and block descriptor table\n try self.seek(block: self.groupDescriptorBlocks + 1)\n // lost+found directory is required for e2fsck to pass\n try self.create(path: FilePath(\"/lost+found\"), mode: Inode.Mode(.S_IFDIR, 0o700))\n }\n\n // Creates a hard link at the path specified by `link` that points to the same file or directory as the path specified by `target`.\n //\n // A hard link is a directory entry that points to the same inode as another directory entry. It allows multiple paths to refer to the same file on the file system.\n //\n // - `link`: The path at which to create the new hard link.\n // - `target`: The path of the existing file or directory to which the hard link should point.\n //\n // Throws an error if `target` path does not exist, or `target` is a directory.\n public func link(\n link: FilePath,\n target: FilePath\n ) throws {\n // ensure that target exists\n guard let targetPtr = self.tree.lookup(path: target) else {\n throw Error.notFound(target)\n }\n let targetNode = targetPtr.pointee\n let targetInodePtr = self.inodes[Int(targetNode.inode) - 1]\n var targetInode = targetInodePtr.pointee\n // ensure that target is not a directory since hardlinks cannot be\n // created to directories\n if targetInode.mode.isDir() {\n throw Error.cannotCreateHardlinksToDirTarget(link)\n }\n targetInode.linksCount += 1\n targetInodePtr.initialize(to: targetInode)\n let parentPath: FilePath = link.dir\n if self.tree.lookup(path: link) != nil {\n try self.unlink(path: link)\n }\n guard let parentTreeNodePtr = self.tree.lookup(path: parentPath) else {\n throw Error.notFound(parentPath)\n }\n let parentTreeNode = parentTreeNodePtr.pointee\n let parentInodePtr = self.inodes[Int(parentTreeNode.inode) - 1]\n let parentInode = parentInodePtr.pointee\n guard parentInode.linksCount < EXT4.MaxLinks else {\n throw Error.maximumLinksExceeded(parentPath)\n }\n let linkTreeNodePtr = Ptr.allocate(capacity: 1)\n let linkTreeNode = FileTree.FileTreeNode(\n inode: InodeNumber(2), // this field is ignored, using 2 so array operations dont panic\n name: link.base,\n parent: parentTreeNodePtr,\n children: [],\n blocks: nil,\n link: targetNode.inode\n )\n linkTreeNodePtr.initialize(to: linkTreeNode)\n parentTreeNode.children.append(linkTreeNodePtr)\n parentTreeNodePtr.initialize(to: parentTreeNode)\n }\n\n // Deletes the file or directory at the specified path from the filesystem.\n //\n // It performs the following actions\n // - set link count of the file's inode to 0\n // - recursively set link count to 0 for its children\n // - free the inode\n // - free data blocks\n // - remove directory entry\n //\n // - `path`: The `FilePath` specifying the path of the file or directory to delete.\n public func unlink(path: FilePath, directoryWhiteout: Bool = false) throws {\n guard let pathPtr = self.tree.lookup(path: path) else {\n // We are being asked to unlink something that does not exist. Ignore\n return\n }\n let pathNode = pathPtr.pointee\n let inodeNumber = Int(pathNode.inode) - 1\n let pathInodePtr = self.inodes[inodeNumber]\n var pathInode = pathInodePtr.pointee\n\n if directoryWhiteout && !pathInode.mode.isDir() {\n throw Error.notDirectory(path)\n }\n\n for childPtr in pathNode.children {\n try self.unlink(path: path.join(childPtr.pointee.name))\n }\n\n guard !directoryWhiteout else {\n return\n }\n\n if let parentNodePtr = self.tree.lookup(path: path.dir) {\n let parentNode = parentNodePtr.pointee\n let parentInodePtr = self.inodes[Int(parentNode.inode) - 1]\n var parentInode = parentInodePtr.pointee\n if pathInode.mode.isDir() {\n if parentInode.linksCount > 2 {\n parentInode.linksCount -= 1\n }\n }\n parentInodePtr.initialize(to: parentInode)\n parentNode.children.removeAll { childPtr in\n childPtr.pointee.name == path.base\n }\n parentNodePtr.initialize(to: parentNode)\n }\n\n if let hardlink = pathNode.link {\n // the file we are deleting is a hardlink, decrement the link count\n let linkedInodePtr = self.inodes[Int(hardlink - 1)]\n var linkedInode = linkedInodePtr.pointee\n if linkedInode.linksCount > 2 {\n linkedInode.linksCount -= 1\n linkedInodePtr.initialize(to: linkedInode)\n }\n }\n\n guard inodeNumber > FirstInode else {\n // Free the inodes and the blocks related to the inode only if its valid\n return\n }\n if let blocks = pathNode.blocks {\n if !(blocks.start == blocks.end) {\n self.deletedBlocks.append((start: blocks.start, end: blocks.end))\n }\n }\n for block in pathNode.additionalBlocks ?? [] {\n self.deletedBlocks.append((start: block.start, end: block.end))\n }\n let now = Date().fs()\n pathInode = Inode()\n pathInode.dtime = now.lo\n pathInodePtr.initialize(to: pathInode)\n }\n\n // Creates a file, directory, or symlink at the specified path, recursively creating parent directories if they don't already exist.\n //\n // - Parameters:\n // - path: The FilePath representing the path where the file, directory, or symlink should be created.\n // - link: An optional FilePath representing the target path for a symlink. If `nil`, a regular file or directory will be created. Preceding '/' should be omitted\n // - mode: The permissions to set for the created file, directory, or symlink.\n // - buf: An `InputStream` object providing the contents for the created file. Ignored when creating directories or symlinks.\n //\n // - Note:\n // - This function recursively creates parent directories if they don't already exist. The `uid` and `gid` of the created parent directories are set to the values of their parent's `uid` and `gid`.\n // - It is expected that the user sets the permissions explicitly later\n // - This function only supports creating files, directories, and symlinks. Attempting to create other types of file system objects will result in an error.\n // - In case of symlinks, the preceding '/' should be omitted\n //\n // - Example usage:\n // ```swift\n // let formatter = EXT4.Formatter(devicePath: \"ext4.img\")\n // // create a directory\n // try formatter.create(path: FilePath(\"/dir\"),\n // mode: EXT4.Inode.Mode(.S_IFDIR, 0o700))\n //\n // // create a file\n // let inputStream = InputStream(data: \"data\".data(using: .utf8)!)\n // inputStream.open()\n // try formatter.create(path: FilePath(\"/dir/file\"),\n // mode: EXT4.Inode.Mode(.S_IFREG, 0o755), buf: inputStream)\n // inputStream.close()\n //\n // // create a symlink\n // try formatter.create(path: FilePath(\"/symlink\"), link: \"/dir/file\",\n // mode: EXT4.Inode.Mode(.S_IFLNK, 0o700))\n // ```\n public func create(\n path: FilePath,\n link: FilePath? = nil, // to create symbolic links\n mode: UInt16,\n ts: FileTimestamps = FileTimestamps(),\n buf: InputStream? = nil,\n uid: UInt32? = nil,\n gid: UInt32? = nil,\n xattrs: [String: Data]? = nil,\n recursion: Bool = false\n ) throws {\n if let nodePtr = self.tree.lookup(path: path) {\n let node = nodePtr.pointee\n let inodePtr = self.inodes[Int(node.inode) - 1]\n let inode = inodePtr.pointee\n // Allowed replace\n // -----------------------------\n //\n // Original Type File Directory Symlink\n // ----------------------------------------------\n // File | ✔ | ✘ | ✔\n // Directory | ✘ | ✔ | ✔\n // Symlink | ✔ | ✘ | ✔\n if mode.isDir() {\n if !inode.mode.isDir() {\n guard inode.mode.isLink() else {\n throw Error.notDirectory(path)\n }\n }\n // mkdir -p\n if path.base == node.name {\n guard !recursion else {\n return\n }\n // create a new tree node to replace this one\n var inode = inode\n inode.mode = mode\n if let uid {\n inode.uid = uid.lo\n inode.uidHigh = uid.hi\n }\n if let gid {\n inode.gid = gid.lo\n inode.gidHigh = gid.hi\n }\n inodePtr.initialize(to: inode)\n return\n }\n } else if let _ = node.link { // ok to overwrite links\n try self.unlink(path: path)\n } else { // file can only be overwritten by another file\n if inode.mode.isDir() {\n guard mode.isLink() else { // unless it is a link, then it can be replaced by a dir\n throw Error.notFile(path)\n }\n }\n try self.unlink(path: path)\n }\n }\n // create all predecessors recursively\n let parentPath: FilePath = path.dir\n try self.create(path: parentPath, mode: Inode.Mode(.S_IFDIR, 0o755), recursion: true)\n guard let parentTreeNodePtr = self.tree.lookup(path: parentPath) else {\n throw Error.notFound(parentPath)\n }\n let parentTreeNode = parentTreeNodePtr.pointee\n let parentInodePtr = self.inodes[Int(parentTreeNode.inode) - 1]\n var parentInode = parentInodePtr.pointee\n guard parentInode.linksCount < EXT4.MaxLinks else {\n throw Error.maximumLinksExceeded(parentPath)\n }\n\n let childInodePtr = Ptr.allocate(capacity: 1)\n var childInode = Inode()\n var startBlock: UInt32 = 0\n var endBlock: UInt32 = 0\n defer { // update metadata\n childInodePtr.initialize(to: childInode)\n parentInodePtr.initialize(to: parentInode)\n self.inodes.append(childInodePtr)\n let childTreeNodePtr = Ptr.allocate(capacity: 1)\n let childTreeNode = FileTree.FileTreeNode(\n inode: InodeNumber(self.inodes.count),\n name: path.base,\n parent: parentTreeNodePtr,\n children: [],\n blocks: (startBlock, endBlock)\n )\n childTreeNodePtr.initialize(to: childTreeNode)\n parentTreeNode.children.append(childTreeNodePtr)\n parentTreeNodePtr.initialize(to: parentTreeNode)\n }\n childInode.mode = mode\n // uid,gid\n if let uid {\n childInode.uid = UInt16(uid & 0xffff)\n childInode.uidHigh = UInt16((uid >> 16) & 0xffff)\n } else {\n childInode.uid = parentInode.uid\n childInode.uidHigh = parentInode.uidHigh\n }\n if let gid {\n childInode.gid = UInt16(gid & 0xffff)\n childInode.gidHigh = UInt16((gid >> 16) & 0xffff)\n } else {\n childInode.gid = parentInode.gid\n childInode.gidHigh = parentInode.gidHigh\n }\n if let xattrs, !xattrs.isEmpty {\n var state = FileXattrsState(\n inode: UInt32(self.inodes.count), inodeXattrCapacity: EXT4.InodeExtraSize, blockCapacity: blockSize)\n try state.add(ExtendedAttribute(name: \"system.data\", value: []))\n for (s, d) in xattrs {\n let attribute = ExtendedAttribute(name: s, value: [UInt8](d))\n try state.add(attribute)\n }\n if !state.inlineAttributes.isEmpty {\n var buffer: [UInt8] = .init(repeating: 0, count: Int(EXT4.InodeExtraSize))\n try state.writeInlineAttributes(buffer: &buffer)\n childInode.inlineXattrs = (\n buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5], buffer[6], buffer[7],\n buffer[8],\n buffer[9],\n buffer[10], buffer[11], buffer[12], buffer[13], buffer[14], buffer[15], buffer[16], buffer[17],\n buffer[18],\n buffer[19],\n buffer[20], buffer[21], buffer[22], buffer[23], buffer[24], buffer[25], buffer[26], buffer[27],\n buffer[28],\n buffer[29],\n buffer[30], buffer[31], buffer[32], buffer[33], buffer[34], buffer[35], buffer[36], buffer[37],\n buffer[38],\n buffer[39],\n buffer[40], buffer[41], buffer[42], buffer[43], buffer[44], buffer[45], buffer[46], buffer[47],\n buffer[48],\n buffer[49],\n buffer[50], buffer[51], buffer[52], buffer[53], buffer[54], buffer[55], buffer[56], buffer[57],\n buffer[58],\n buffer[59],\n buffer[60], buffer[61], buffer[62], buffer[63], buffer[64], buffer[65], buffer[66], buffer[67],\n buffer[68],\n buffer[69],\n buffer[70], buffer[71], buffer[72], buffer[73], buffer[74], buffer[75], buffer[76], buffer[77],\n buffer[78],\n buffer[79],\n buffer[80], buffer[81], buffer[82], buffer[83], buffer[84], buffer[85], buffer[86], buffer[87],\n buffer[88],\n buffer[89],\n buffer[90], buffer[91], buffer[92], buffer[93], buffer[94], buffer[95]\n )\n childInode.flags |= InodeFlag.inlineData.rawValue\n }\n if !state.blockAttributes.isEmpty {\n var buffer: [UInt8] = .init(repeating: 0, count: Int(blockSize))\n try state.writeBlockAttributes(buffer: &buffer)\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n childInode.xattrBlockLow = self.currentBlock\n try self.handle.write(contentsOf: buffer)\n childInode.blocksLow += 1\n }\n }\n\n childInode.atime = ts.accessLo\n childInode.atimeExtra = ts.accessHi\n // ctime is the last time the inode was changed which is now\n childInode.ctime = ts.nowLo\n childInode.ctimeExtra = ts.nowHi\n childInode.mtime = ts.modificationLo\n childInode.mtimeExtra = ts.modificationHi\n childInode.crtime = ts.creationLo\n childInode.crtimeExtra = ts.creationHi\n childInode.linksCount = 1\n childInode.extraIsize = UInt16(EXT4.ExtraIsize)\n // flags\n childInode.flags = InodeFlag.hugeFile.rawValue\n // size check\n var size: UInt64 = 0\n // align with block boundary\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n // dir\n if childInode.mode.isDir() {\n childInode.linksCount += 1\n parentInode.linksCount += 1\n // to pass e2fsck, the convention is to sort children\n // before committing to disk. Therefore, we are deferring\n // writing dentries until commit() is called\n return\n }\n // symbolic link\n if let link {\n startBlock = self.currentBlock\n let linkPath = link.bytes\n if linkPath.count < 60 {\n size += UInt64(linkPath.count)\n var blockData: [UInt8] = .init(repeating: 0, count: 60)\n for i in 0...allocate(capacity: Int(self.blockSize))\n defer { tempBuf.deallocate() }\n while case let block = buf.read(tempBuf.underlying, maxLength: Int(self.blockSize)), block > 0 {\n size += UInt64(block)\n if size > EXT4.MaxFileSize {\n throw Error.fileTooBig(size)\n }\n let data = UnsafeRawBufferPointer(start: tempBuf.underlying, count: block)\n try withUnsafeLittleEndianBuffer(of: data) { b in\n try self.handle.write(contentsOf: b)\n }\n }\n }\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n endBlock = self.currentBlock\n childInode.sizeLow = size.lo\n childInode.sizeHigh = size.hi\n childInode = try self.writeExtents(childInode, (startBlock, endBlock))\n return\n }\n // FIFO, Socket and other types are not handled\n throw Error.unsupportedFiletype\n }\n\n public func setOwner(path: FilePath, uid: UInt16? = nil, gid: UInt16? = nil, recursive: Bool = false) throws {\n // ensure that target exists\n guard let pathPtr = self.tree.lookup(path: path) else {\n throw Error.notFound(path)\n }\n let pathNode = pathPtr.pointee\n let pathInodePtr = self.inodes[Int(pathNode.inode) - 1]\n var pathInode = pathInodePtr.pointee\n if let uid {\n pathInode.uid = uid\n }\n if let gid {\n pathInode.gid = gid\n }\n pathInodePtr.initialize(to: pathInode)\n if recursive {\n for childPtr in pathNode.children {\n let child = childPtr.pointee\n try self.setOwner(path: path.join(child.name), uid: uid, gid: gid, recursive: recursive)\n }\n }\n }\n\n // Completes the formatting of an ext4 filesystem after writing the necessary structures.\n //\n // This function is responsible for finalizing the formatting process of an ext4 filesystem\n // after the following structures have been written:\n // - Inode table: Contains information about each file and directory in the filesystem.\n // - Block bitmap: Tracks the allocation status of each block in the filesystem.\n // - Inode bitmap: Tracks the allocation status of each inode in the filesystem.\n // - Directory tree: Represents the hierarchical structure of directories and files.\n // - Group descriptors: Stores metadata about each block group in the filesystem.\n // - Superblock: Contains essential information about the filesystem's configuration.\n //\n // The function performs any necessary final steps to ensure the integrity and consistency\n // of the ext4 filesystem before it can be mounted and used.\n public func close() throws {\n var breathWiseChildTree: [(parent: Ptr?, child: Ptr)] = [\n (nil, self.tree.root)\n ]\n while !breathWiseChildTree.isEmpty {\n let (parent, child) = breathWiseChildTree.removeFirst()\n try self.commit(parent, child) // commit directories iteratively\n if child.pointee.link != nil {\n continue\n }\n breathWiseChildTree.append(contentsOf: child.pointee.children.map { (child, $0) })\n }\n let blockGroupSize = optimizeBlockGroupLayout(blocks: self.currentBlock, inodes: UInt32(self.inodes.count))\n let inodeTableOffset = try self.commitInodeTable(\n blockGroups: blockGroupSize.blockGroups,\n inodesPerGroup: blockGroupSize.inodesPerGroup\n )\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n // write bitmaps and group descriptors\n\n let bitmapOffset = self.currentBlock\n let bitmapSize: UInt32 = blockGroupSize.blockGroups * 2 // each group has two bitmaps - for inodes, and for blocks\n let dataSize: UInt32 = bitmapOffset + bitmapSize // last data block\n var diskSize = dataSize\n var minimumDiskSize = (blockGroupSize.blockGroups - 1) * self.blocksPerGroup + 1\n if blockGroupSize.blockGroups == 1 {\n minimumDiskSize = self.blocksPerGroup // at least 1 block group\n }\n if diskSize < minimumDiskSize { // for data + metadata\n diskSize = minimumDiskSize\n }\n if self.size < minimumDiskSize {\n self.size = UInt64(minimumDiskSize) * self.blockSize\n }\n // number of blocks needed for group descriptors\n let groupDescriptorBlockCount: UInt32 = (blockGroupSize.blockGroups - 1) / self.groupsPerDescriptorBlock + 1\n guard groupDescriptorBlockCount <= self.groupDescriptorBlocks else {\n throw Error.insufficientSpaceForGroupDescriptorBlocks\n }\n\n var totalBlocks: UInt32 = 0\n var totalInodes: UInt32 = 0\n let inodeTableSizePerGroup: UInt32 = blockGroupSize.inodesPerGroup * EXT4.InodeSize / self.blockSize\n var groupDescriptors: [GroupDescriptor] = []\n\n let minGroups = (((self.pos / UInt64(self.blockSize)) - 1) / UInt64(self.blocksPerGroup)) + 1\n if self.size < minGroups * blocksPerGroup * blockSize {\n self.size = UInt64(minGroups * blocksPerGroup * blockSize)\n let pos = self.pos\n guard lseek(self.handle.fileDescriptor, off_t(self.size - 1), 0) == self.size - 1 else {\n throw Error.cannotResizeFS(self.size)\n }\n let zero: [UInt8] = [0]\n try self.handle.write(contentsOf: zero)\n try self.handle.seek(toOffset: pos)\n }\n let totalGroups = (((self.size / UInt64(self.blockSize)) - 1) / UInt64(self.blocksPerGroup)) + 1\n\n // If the provided disk size is not aligned to a blockgroup boundary, it needs to\n // be expanded to the next blockgroup boundary.\n // Example:\n // Provided disk size: 2 GB + 100MB: 2148 MB\n // BlockSize: 4096\n // Blockgroup size: 32768 blocks: 128MB\n // Number of blocks: 549888\n // Number of blockgroups = 549888 / 32768 = 16.78125\n // Aligned disk size = 557056 blocks = 17 blockgroups: 2176 MB\n if self.size < totalGroups * blocksPerGroup * blockSize {\n self.size = UInt64(totalGroups * blocksPerGroup * blockSize)\n let pos = self.pos\n guard lseek(self.handle.fileDescriptor, off_t(self.size - 1), 0) == self.size - 1 else {\n throw Error.cannotResizeFS(self.size)\n }\n let zero: [UInt8] = [0]\n try self.handle.write(contentsOf: zero)\n try self.handle.seek(toOffset: pos)\n }\n for group in 0..> (j % 8)) & 1)\n bitmap[Int(j / 8)] &= ~(1 << (j % 8))\n }\n }\n\n // inodes bitmap goes into second bitmap block\n for i in 0.. self.inodes.count {\n continue\n }\n let inode = self.inodes[Int(ino) - 1]\n if ino > 10 && inode.pointee.linksCount == 0 { // deleted files\n continue\n }\n bitmap[Int(self.blockSize) + Int(i / 8)] |= 1 << (i % 8)\n inodes += 1\n if inode.pointee.mode.isDir() {\n dirs += 1\n }\n }\n\n for i in (blockGroupSize.inodesPerGroup / 8)...init(repeating: 0, count: 1024))\n\n let computedInodes = totalGroups * blockGroupSize.inodesPerGroup\n var blocksCount = totalGroups * self.blocksPerGroup\n while blocksCount < totalBlocks {\n blocksCount = UInt64(totalBlocks)\n }\n let totalFreeBlocks: UInt64\n if totalBlocks > blocksCount {\n totalFreeBlocks = 0\n } else {\n totalFreeBlocks = blocksCount - totalBlocks\n }\n var superblock = SuperBlock()\n superblock.inodesCount = computedInodes.lo\n superblock.blocksCountLow = blocksCount.lo\n superblock.blocksCountHigh = blocksCount.hi\n superblock.freeBlocksCountLow = totalFreeBlocks.lo\n superblock.freeBlocksCountHigh = totalFreeBlocks.hi\n let freeInodesCount = computedInodes.lo - totalInodes\n superblock.freeInodesCount = freeInodesCount\n superblock.firstDataBlock = 0\n superblock.logBlockSize = 2\n superblock.logClusterSize = 2\n superblock.blocksPerGroup = self.blocksPerGroup\n superblock.clustersPerGroup = self.blocksPerGroup\n superblock.inodesPerGroup = blockGroupSize.inodesPerGroup\n superblock.magic = EXT4.SuperBlockMagic\n superblock.state = 1 // cleanly unmounted\n superblock.errors = 1 // continue on error\n superblock.creatorOS = 3 // freeBSD\n superblock.revisionLevel = 1 // dynamic inode sizes\n superblock.firstInode = EXT4.FirstInode\n superblock.lpfInode = EXT4.LostAndFoundInode\n superblock.inodeSize = UInt16(EXT4.InodeSize)\n superblock.featureCompat = CompatFeature.sparseSuper2 | CompatFeature.extAttr\n superblock.featureIncompat =\n IncompatFeature.filetype | IncompatFeature.extents | IncompatFeature.flexBg | IncompatFeature.inlineData\n superblock.featureRoCompat =\n RoCompatFeature.largeFile | RoCompatFeature.hugeFile | RoCompatFeature.extraIsize\n superblock.minExtraIsize = EXT4.ExtraIsize\n superblock.wantExtraIsize = EXT4.ExtraIsize\n superblock.logGroupsPerFlex = 31\n superblock.uuid = UUID().uuid\n try withUnsafeLittleEndianBytes(of: superblock) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n try self.handle.write(contentsOf: Array.init(repeating: 0, count: 2048))\n }\n\n // MARK: Private Methods and Properties\n private var handle: FileHandle\n private var inodes: [Ptr]\n private var tree: FileTree\n private var deletedBlocks: [(start: UInt32, end: UInt32)] = []\n\n private var pos: UInt64 {\n guard let offset = try? self.handle.offset() else {\n return 0\n }\n return offset\n }\n\n private var currentBlock: UInt32 {\n self.pos / self.blockSize\n }\n\n private func seek(block: UInt32) throws {\n try self.handle.seek(toOffset: UInt64(block) * blockSize)\n }\n\n private func commitInodeTable(blockGroups: UInt32, inodesPerGroup: UInt32) throws -> UInt64 {\n // inodeTable must go into a new block\n if self.pos % blockSize != 0 {\n try seek(block: currentBlock + 1)\n }\n let inodeTableOffset = UInt64(currentBlock)\n\n let inodeSize = MemoryLayout.size\n // Write InodeTable\n for inode in self.inodes {\n try withUnsafeLittleEndianBytes(of: inode.pointee) { bytes in\n try handle.write(contentsOf: bytes)\n }\n try self.handle.write(\n contentsOf: Array.init(repeating: 0, count: Int(EXT4.InodeSize) - inodeSize))\n }\n let tableSize: UInt64 = UInt64(EXT4.InodeSize) * blockGroups * inodesPerGroup\n let rest = tableSize - uint32(self.inodes.count) * EXT4.InodeSize\n let zeroBlock = Array.init(repeating: 0, count: Int(self.blockSize))\n for _ in 0..<(rest / self.blockSize) {\n try self.handle.write(contentsOf: zeroBlock)\n }\n try self.handle.write(contentsOf: Array.init(repeating: 0, count: Int(rest % self.blockSize)))\n return inodeTableOffset\n }\n\n // optimizes the distribution of blockGroups to obtain the lowest number of blockGroups needed to\n // represent all the inodes and all the blocks in the FS\n private func optimizeBlockGroupLayout(blocks: UInt32, inodes: UInt32) -> (\n blockGroups: UInt32, inodesPerGroup: UInt32\n ) {\n // counts the number of blockGroups given a particular inodesPerGroup size\n let groupCount: (_ blocks: UInt32, _ inodes: UInt32, _ inodesPerGroup: UInt32) -> UInt32 = {\n blocks, inodes, inodesPerGroup in\n let inodeBlocksPerGroup: UInt32 = inodesPerGroup * EXT4.InodeSize / self.blockSize\n let dataBlocksPerGroup: UInt32 = self.blocksPerGroup - inodeBlocksPerGroup - 2 // save room for the bitmaps\n // Increase the block count to ensure there are enough groups for all the inodes.\n let minBlocks: UInt32 = (inodes - 1) / inodesPerGroup * dataBlocksPerGroup + 1\n var updatedBlocks = blocks\n if blocks < minBlocks {\n updatedBlocks = minBlocks\n }\n return (updatedBlocks + dataBlocksPerGroup - 1) / dataBlocksPerGroup\n }\n\n var groups: UInt32 = UInt32.max\n var inodesPerGroup: UInt32 = 0\n let inc = Int(self.blockSize * 512) / Int(EXT4.InodeSize) // inodesPerGroup\n // minimizes the number of blockGroups needed to its lowest value\n for ipg in stride(from: inc, through: Int(self.maxInodesPerGroup), by: inc) {\n let g = groupCount(blocks, inodes, UInt32(ipg))\n if g < groups {\n groups = g\n inodesPerGroup = UInt32(ipg)\n }\n }\n return (groups, inodesPerGroup)\n }\n\n private func commit(_ parentPtr: Ptr?, _ nodePtr: Ptr) throws {\n let node = nodePtr.pointee\n let inodePtr = self.inodes[Int(node.inode) - 1]\n var inode = inodePtr.pointee\n guard inode.linksCount > 0 else {\n return\n }\n if node.link != nil {\n return\n }\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n if inode.mode.isDir() {\n let startBlock = self.currentBlock\n var left: Int = Int(self.blockSize)\n try writeDirEntry(name: \".\", inode: node.inode, left: &left)\n if let parent = parentPtr {\n try writeDirEntry(name: \"..\", inode: parent.pointee.inode, left: &left)\n } else {\n try writeDirEntry(name: \"..\", inode: node.inode, left: &left)\n }\n var sortedChildren = Array(node.children)\n sortedChildren.sort { left, right in\n left.pointee.inode < right.pointee.inode\n }\n for childPtr in sortedChildren {\n let child = childPtr.pointee\n try writeDirEntry(name: child.name, inode: child.inode, left: &left, link: child.link)\n }\n try finishDirEntryBlock(&left)\n let endBlock = self.currentBlock\n let size: UInt64 = UInt64(endBlock - startBlock) * self.blockSize\n inode.sizeLow = size.lo\n inode.sizeHigh = size.hi\n inodePtr.initialize(to: inode)\n node.blocks = (startBlock, endBlock)\n nodePtr.initialize(to: node)\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n inode = try self.writeExtents(inode, (startBlock, endBlock))\n inodePtr.initialize(to: inode)\n }\n }\n\n private func fillExtents(\n node: inout ExtentLeafNode, numExtents: UInt32, numBlocks: UInt32, start: UInt32, offset: UInt32\n ) {\n for i in 0.. EXT4.MaxBlocksPerExtent {\n length = EXT4.MaxBlocksPerExtent\n }\n let extentStart: UInt32 = start + extentBlock\n let extent = ExtentLeaf(\n block: extentBlock,\n length: UInt16(length),\n startHigh: 0,\n startLow: extentStart\n )\n node.leaves.append(extent)\n }\n }\n\n private func writeExtents(_ inode: Inode, _ blocks: (start: UInt32, end: UInt32)) throws -> Inode {\n var inode = inode\n // rest of code assumes that extents MUST go into a new block\n if self.pos % self.blockSize != 0 {\n try self.seek(block: self.currentBlock + 1)\n }\n let dataBlocks = blocks.end - blocks.start\n let numExtents = (dataBlocks + EXT4.MaxBlocksPerExtent - 1) / EXT4.MaxBlocksPerExtent\n var usedBlocks = dataBlocks\n let extentNodeSize = 12\n let extentsPerBlock = self.blockSize / extentNodeSize - 1\n var blockData: [UInt8] = .init(repeating: 0, count: 60)\n var blockIndex: Int = 0\n switch numExtents {\n case 0:\n return inode // noop\n case 1..<5:\n let extentHeader = ExtentHeader(\n magic: EXT4.ExtentHeaderMagic,\n entries: UInt16(numExtents),\n max: 4,\n depth: 0,\n generation: 0)\n\n var node = ExtentLeafNode(header: extentHeader, leaves: [])\n fillExtents(node: &node, numExtents: numExtents, numBlocks: dataBlocks, start: blocks.start, offset: 0)\n withUnsafeLittleEndianBytes(of: node.header) { bytes in\n for b in bytes {\n blockData[blockIndex] = b\n blockIndex = blockIndex + 1\n }\n }\n for leaf in node.leaves {\n withUnsafeLittleEndianBytes(of: leaf) { bytes in\n for b in bytes {\n blockData[blockIndex] = b\n blockIndex = blockIndex + 1\n }\n }\n }\n case 5..<4 * UInt32(extentsPerBlock) + 1:\n let extentBlocks = numExtents / extentsPerBlock + 1\n usedBlocks += extentBlocks\n let extentHeader = ExtentHeader(\n magic: EXT4.ExtentHeaderMagic,\n entries: UInt16(extentBlocks),\n max: 4,\n depth: 1,\n generation: 0\n )\n var root = ExtentIndexNode(header: extentHeader, indices: [])\n for i in 0.. extentsPerBlock {\n extentsInBlock = extentsPerBlock\n }\n let leafHeader = ExtentHeader(\n magic: EXT4.ExtentHeaderMagic,\n entries: UInt16(extentsInBlock),\n max: UInt16(extentsPerBlock),\n depth: 0,\n generation: 0\n )\n var leafNode = ExtentLeafNode(header: leafHeader, leaves: [])\n let offset = i * extentsPerBlock * EXT4.MaxBlocksPerExtent\n fillExtents(\n node: &leafNode, numExtents: extentsInBlock, numBlocks: dataBlocks,\n start: blocks.start + offset,\n offset: offset)\n try withUnsafeLittleEndianBytes(of: leafNode.header) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n for leaf in leafNode.leaves {\n try withUnsafeLittleEndianBytes(of: leaf) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n }\n let extentTail = ExtentTail(checksum: leafNode.leaves.last!.block)\n try withUnsafeLittleEndianBytes(of: extentTail) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n root.indices.append(extentIdx)\n }\n withUnsafeLittleEndianBytes(of: root.header) { bytes in\n for b in bytes {\n blockData[blockIndex] = b\n blockIndex = blockIndex + 1\n }\n }\n for leaf in root.indices {\n withUnsafeLittleEndianBytes(of: leaf) { bytes in\n for b in bytes {\n blockData[blockIndex] = b\n blockIndex = blockIndex + 1\n }\n }\n }\n default:\n throw Error.fileTooBig(UInt64(dataBlocks) * self.blockSize)\n }\n inode.block = (\n blockData[0], blockData[1], blockData[2], blockData[3], blockData[4], blockData[5], blockData[6],\n blockData[7],\n blockData[8], blockData[9],\n blockData[10], blockData[11], blockData[12], blockData[13], blockData[14], blockData[15], blockData[16],\n blockData[17], blockData[18], blockData[19],\n blockData[20], blockData[21], blockData[22], blockData[23], blockData[24], blockData[25], blockData[26],\n blockData[27], blockData[28], blockData[29],\n blockData[30], blockData[31], blockData[32], blockData[33], blockData[34], blockData[35], blockData[36],\n blockData[37], blockData[38], blockData[39],\n blockData[40], blockData[41], blockData[42], blockData[43], blockData[44], blockData[45], blockData[46],\n blockData[47], blockData[48], blockData[49],\n blockData[50], blockData[51], blockData[52], blockData[53], blockData[54], blockData[55], blockData[56],\n blockData[57], blockData[58], blockData[59]\n )\n // ensure that inode's block count includes extent blocks\n inode.blocksLow += usedBlocks\n inode.flags = InodeFlag.extents | inode.flags\n return inode\n }\n // writes a single directory entry\n private func writeDirEntry(name: String, inode: InodeNumber, left: inout Int, link: InodeNumber? = nil) throws {\n guard self.inodes[Int(inode) - 1].pointee.linksCount > 0 else {\n return\n }\n guard let nameData = name.data(using: .utf8) else {\n throw Error.invalidName(name)\n }\n let directoryEntrySize = MemoryLayout.size\n let rlb = directoryEntrySize + nameData.count\n let rl = (rlb + 3) & ~3\n if left < rl + 12 {\n try self.finishDirEntryBlock(&left)\n }\n var mode = self.inodes[Int(inode) - 1].pointee.mode\n var inodeNum = inode\n if let link {\n mode = self.inodes[Int(link) - 1].pointee.mode | 0o777\n inodeNum = link\n }\n let entry = DirectoryEntry(\n inode: inodeNum,\n recordLength: UInt16(rl),\n nameLength: UInt8(nameData.count),\n fileType: mode.fileType()\n )\n try withUnsafeLittleEndianBytes(of: entry) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n\n try nameData.withUnsafeBytes { buffer in\n try withUnsafeLittleEndianBuffer(of: buffer) { b in\n try self.handle.write(contentsOf: b)\n }\n }\n try self.handle.write(contentsOf: [UInt8](repeating: 0, count: rl - rlb))\n left = left - rl\n }\n\n private func finishDirEntryBlock(_ left: inout Int) throws {\n defer { left = Int(self.blockSize) }\n if left <= 0 {\n return\n }\n let entry = DirectoryEntry(\n inode: InodeNumber(0),\n recordLength: UInt16(left),\n nameLength: 0,\n fileType: 0\n )\n try withUnsafeLittleEndianBytes(of: entry) { bytes in\n try self.handle.write(contentsOf: bytes)\n }\n left = left - MemoryLayout.size\n if left < 4 {\n throw Error.noSpaceForTrailingDEntry\n }\n try self.handle.write(contentsOf: [UInt8](repeating: 0, count: Int(left)))\n }\n\n public enum Error: Swift.Error, CustomStringConvertible, Sendable, Equatable {\n case notDirectory(_ path: FilePath)\n case notFile(_ path: FilePath)\n case notFound(_ path: FilePath)\n case alreadyExists(_ path: FilePath)\n case unsupportedFiletype\n case maximumLinksExceeded(_ path: FilePath)\n case fileTooBig(_ size: UInt64)\n case invalidLink(_ path: FilePath)\n case invalidName(_ name: String)\n case noSpaceForTrailingDEntry\n case insufficientSpaceForGroupDescriptorBlocks\n case cannotCreateHardlinksToDirTarget(_ path: FilePath)\n case cannotTruncateFile(_ path: FilePath)\n case cannotCreateSparseFile(_ path: FilePath)\n case cannotResizeFS(_ size: UInt64)\n public var description: String {\n switch self {\n case .notDirectory(let path):\n return \"\\(path) is not a directory\"\n case .notFile(let path):\n return \"\\(path) is not a file\"\n case .notFound(let path):\n return \"\\(path) not found\"\n case .alreadyExists(let path):\n return \"\\(path) already exists\"\n case .unsupportedFiletype:\n return \"file type not supported\"\n case .maximumLinksExceeded(let path):\n return \"maximum links exceeded for path: \\(path)\"\n case .fileTooBig(let size):\n return \"\\(size) exceeds max file size (128 GiB)\"\n case .invalidLink(let path):\n return \"'\\(path)' is an invalid link\"\n case .invalidName(let name):\n return \"'\\(name)' is an invalid name\"\n case .noSpaceForTrailingDEntry:\n return \"not enough space for trailing dentry\"\n case .insufficientSpaceForGroupDescriptorBlocks:\n return \"not enough space for group descriptor blocks\"\n case .cannotCreateHardlinksToDirTarget(let path):\n return \"cannot create hard links to directory target: \\(path)\"\n case .cannotTruncateFile(let path):\n return \"cannot truncate file: \\(path)\"\n case .cannotCreateSparseFile(let path):\n return \"cannot create sparse file at \\(path)\"\n case .cannotResizeFS(let size):\n return \"cannot resize fs to \\(size) bytes\"\n }\n }\n }\n\n deinit {\n for inode in inodes {\n inode.deinitialize(count: 1)\n inode.deallocate()\n }\n self.inodes.removeAll()\n }\n }\n}\n\nextension Date {\n func fs() -> UInt64 {\n if self == Date.distantPast {\n return 0\n }\n\n let s = self.timeIntervalSince1970\n\n if s < -0x8000_0000 {\n return 0x8000_0000\n }\n\n if s > 0x3_7fff_ffff {\n return 0x3_7fff_ffff\n }\n\n let seconds = UInt64(s)\n let nanoseconds = UInt64(self.timeIntervalSince1970.truncatingRemainder(dividingBy: 1) * 1_000_000_000)\n\n return seconds | (nanoseconds << 34)\n }\n}\n"], ["/containerization/vminitd/Sources/vmexec/vmexec.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// NOTE: This binary implements a very small subset of the OCI runtime spec, mostly just\n/// the process configurations. Mounts are somewhat functional, but masked and read only paths\n/// aren't checked today. Today the namespaces are also ignored, and we always spawn a new pid\n/// and mount namespace.\n\nimport ArgumentParser\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\nimport LCShim\nimport Logging\nimport Musl\n\n@main\nstruct App: ParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"vmexec\",\n version: \"0.1.0\",\n subcommands: [\n ExecCommand.self,\n RunCommand.self,\n ]\n )\n\n static let standardErrorLock = NSLock()\n\n @Sendable\n static func standardError(label: String) -> StreamLogHandler {\n standardErrorLock.withLock {\n StreamLogHandler.standardError(label: label)\n }\n }\n}\n\nextension App {\n /// Applies O_CLOEXEC to all file descriptors currently open for\n /// the process except the stdio fd values\n static func applyCloseExecOnFDs() throws {\n let minFD = 2 // stdin, stdout, stderr should be preserved\n\n let fdList = try FileManager.default.contentsOfDirectory(atPath: \"/proc/self/fd\")\n\n for fdStr in fdList {\n guard let fd = Int(fdStr) else {\n continue\n }\n if fd <= minFD {\n continue\n }\n\n _ = fcntl(Int32(fd), F_SETFD, FD_CLOEXEC)\n }\n }\n\n static func exec(process: ContainerizationOCI.Process) throws {\n let executable = strdup(process.args[0])\n var argv = process.args.map { strdup($0) }\n argv += [nil]\n\n let env = process.env.map { strdup($0) } + [nil]\n let cwd = process.cwd\n\n // switch cwd\n guard chdir(cwd) == 0 else {\n throw App.Errno(stage: \"chdir(cwd)\", info: \"Failed to change directory to '\\(cwd)'\")\n }\n\n guard execvpe(executable, argv, env) != -1 else {\n throw App.Errno(stage: \"execvpe(\\(String(describing: executable)))\", info: \"Failed to exec [\\(process.args.joined(separator: \" \"))]\")\n }\n fatalError(\"execvpe failed\")\n }\n\n static func setPermissions(user: ContainerizationOCI.User) throws {\n if user.additionalGids.count > 0 {\n guard setgroups(user.additionalGids.count, user.additionalGids) == 0 else {\n throw App.Errno(stage: \"setgroups()\")\n }\n }\n guard setgid(user.gid) == 0 else {\n throw App.Errno(stage: \"setgid()\")\n }\n // NOTE: setuid has to be done last because once the uid has been\n // changed, then the process will lose privilege to set the group\n // and supplementary groups\n guard setuid(user.uid) == 0 else {\n throw App.Errno(stage: \"setuid()\")\n }\n }\n\n static func fixStdioPerms(user: ContainerizationOCI.User) throws {\n for i in 0...2 {\n var fdStat = stat()\n try withUnsafeMutablePointer(to: &fdStat) { pointer in\n guard fstat(Int32(i), pointer) == 0 else {\n throw App.Errno(stage: \"fstat(fd)\")\n }\n }\n\n let desired = uid_t(user.uid)\n if fdStat.st_uid != desired {\n guard fchown(Int32(i), desired, fdStat.st_gid) != -1 else {\n throw App.Errno(stage: \"fchown(\\(i))\")\n }\n }\n }\n }\n\n static func setRLimits(rlimits: [ContainerizationOCI.POSIXRlimit]) throws {\n for rl in rlimits {\n var limit = rlimit(rlim_cur: rl.soft, rlim_max: rl.hard)\n let resource: Int32\n switch rl.type {\n case \"RLIMIT_AS\":\n resource = RLIMIT_AS\n case \"RLIMIT_CORE\":\n resource = RLIMIT_CORE\n case \"RLIMIT_CPU\":\n resource = RLIMIT_CPU\n case \"RLIMIT_DATA\":\n resource = RLIMIT_DATA\n case \"RLIMIT_FSIZE\":\n resource = RLIMIT_FSIZE\n case \"RLIMIT_NOFILE\":\n resource = RLIMIT_NOFILE\n case \"RLIMIT_STACK\":\n resource = RLIMIT_STACK\n case \"RLIMIT_NPROC\":\n resource = RLIMIT_NPROC\n case \"RLIMIT_RSS\":\n resource = RLIMIT_RSS\n case \"RLIMIT_MEMLOCK\":\n resource = RLIMIT_MEMLOCK\n default:\n errno = EINVAL\n throw App.Errno(stage: \"rlimit key unknown\")\n }\n guard setrlimit(resource, &limit) == 0 else {\n throw App.Errno(stage: \"setrlimit()\")\n }\n }\n }\n\n static func Errno(stage: String, info: String = \"\") -> ContainerizationError {\n let posix = POSIXError(.init(rawValue: errno)!, userInfo: [\"stage\": stage])\n return ContainerizationError(.internalError, message: \"\\(info) \\(String(describing: posix))\")\n }\n}\n"], ["/containerization/Sources/cctl/RootfsCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationArchive\nimport ContainerizationEXT4\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\n\nextension Application {\n struct Rootfs: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"rootfs\",\n abstract: \"Manage the root filesystem for a container\",\n subcommands: [\n Create.self\n ]\n )\n\n struct Create: AsyncParsableCommand {\n @Option(name: .long, help: \"Path to vminitd\")\n var vminitd: String\n\n @Option(name: .long, help: \"Path to vmexec\")\n var vmexec: String\n\n @Option(name: .long, help: \"Platform of the built binaries being packaged into the block\")\n var platformString: String = Platform.current.description\n\n @Option(name: .long, help: \"Labels to add to the built image of the form =, [=,...]\")\n var labels: [String] = []\n\n @Argument var rootfsPath: String\n\n @Argument var tag: String\n\n private static let directories = [\n \"bin\",\n \"sbin\",\n \"dev\",\n \"sys\",\n \"proc/self\", // hack for swift init's booting\n \"run\",\n \"tmp\",\n \"mnt\",\n \"var\",\n ]\n\n func run() async throws {\n try await writeArchive()\n let p = try Platform(from: platformString)\n let rootfs = URL(filePath: rootfsPath)\n let labels = Application.parseKeyValuePairs(from: labels)\n _ = try await InitImage.create(\n reference: tag, rootfs: rootfs,\n platform: p, labels: labels,\n imageStore: Application.imageStore,\n contentStore: Application.contentStore)\n }\n\n private func writeArchive() async throws {\n let writer = try ArchiveWriter(format: .pax, filter: .gzip, file: URL(filePath: rootfsPath))\n let ts = Date()\n let entry = WriteEntry()\n entry.permissions = 0o755\n entry.modificationDate = ts\n entry.creationDate = ts\n entry.group = 0\n entry.owner = 0\n entry.fileType = .directory\n // create the initial directory structure.\n for dir in Self.directories {\n entry.path = dir\n try writer.writeEntry(entry: entry, data: nil)\n }\n\n entry.fileType = .regular\n entry.path = \"sbin/vminitd\"\n\n var src = URL(fileURLWithPath: vminitd)\n var data = try Data(contentsOf: src)\n entry.size = Int64(data.count)\n try writer.writeEntry(entry: entry, data: data)\n\n src = URL(fileURLWithPath: vmexec)\n data = try Data(contentsOf: src)\n entry.path = \"sbin/vmexec\"\n entry.size = Int64(data.count)\n try writer.writeEntry(entry: entry, data: data)\n\n entry.fileType = .symbolicLink\n entry.path = \"proc/self/exe\"\n entry.symlinkTarget = \"sbin/vminitd\"\n entry.size = nil\n try writer.writeEntry(entry: entry, data: data)\n try writer.finishEncoding()\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Socket/VsockType.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CShim\n\n#if canImport(Musl)\nimport Musl\n#elseif canImport(Glibc)\nimport Glibc\n#elseif canImport(Darwin)\nimport Darwin\n#else\n#error(\"VsockType not supported on this platform.\")\n#endif\n\n/// Vsock variant of `SocketType`.\npublic struct VsockType: SocketType, Sendable {\n public var domain: Int32 { AF_VSOCK }\n public var type: Int32 { _SOCK_STREAM }\n public var description: String {\n \"\\(cid):\\(port)\"\n }\n\n public static let anyCID: UInt32 = UInt32(bitPattern: -1)\n public static let hypervisorCID: UInt32 = 0x0\n // Supported on Linux 5.6+; otherwise, will need to use getLocalCID().\n public static let localCID: UInt32 = 0x1\n public static let hostCID: UInt32 = 0x2\n\n // socketFD is unused on Linux.\n public static func getLocalCID(socketFD: Int32) throws -> UInt32 {\n let request = VsockLocalCIDIoctl\n #if os(Linux)\n let fd = open(\"/dev/vsock\", O_RDONLY | O_CLOEXEC)\n if fd == -1 {\n throw Socket.errnoToError(msg: \"failed to open /dev/vsock\")\n }\n defer { close(fd) }\n #else\n let fd = socketFD\n #endif\n var cid: UInt32 = 0\n guard sysIoctl(fd, numericCast(request), &cid) != -1 else {\n throw Socket.errnoToError(msg: \"failed to get local cid\")\n }\n return cid\n }\n\n public let port: UInt32\n public let cid: UInt32\n\n private let _addr: sockaddr_vm\n\n public init(port: UInt32, cid: UInt32) {\n self.cid = cid\n self.port = port\n var sockaddr = sockaddr_vm()\n sockaddr.svm_family = sa_family_t(AF_VSOCK)\n sockaddr.svm_cid = cid\n sockaddr.svm_port = port\n self._addr = sockaddr\n }\n\n private init(sockaddr: sockaddr_vm) {\n self._addr = sockaddr\n self.cid = sockaddr.svm_cid\n self.port = sockaddr.svm_port\n }\n\n public func accept(fd: Int32) throws -> (Int32, SocketType) {\n var clientFD: Int32 = -1\n var addr = sockaddr_vm()\n\n while clientFD < 0 {\n var size = socklen_t(MemoryLayout.stride)\n clientFD = withUnsafeMutablePointer(to: &addr) { pointer in\n pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { pointer in\n sysAccept(fd, pointer, &size)\n }\n }\n if clientFD < 0 && errno != EINTR {\n throw Socket.errnoToError(msg: \"accept failed\")\n }\n }\n return (clientFD, VsockType(sockaddr: addr))\n }\n\n public func withSockAddr(_ closure: (UnsafePointer, UInt32) throws -> Void) throws {\n var addr = self._addr\n try withUnsafePointer(to: &addr) {\n let addrBytes = UnsafeRawPointer($0).assumingMemoryBound(to: sockaddr.self)\n try closure(addrBytes, UInt32(MemoryLayout.stride))\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Mount/Mount.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n#if canImport(Musl)\nimport Musl\nprivate let _mount = Musl.mount\nprivate let _umount = Musl.umount2\n#elseif canImport(Glibc)\nimport Glibc\nprivate let _mount = Glibc.mount\nprivate let _umount = Glibc.umount2\n#endif\n\n// Mount package modeled closely from containerd's: https://github.com/containerd/containerd/tree/main/core/mount\n\n/// `Mount` models a Linux mount (although potentially could be used on other unix platforms), and\n/// provides a simple interface to mount what the type describes.\npublic struct Mount: Sendable {\n // Type specifies the host-specific of the mount.\n public var type: String\n // Source specifies where to mount from. Depending on the host system, this\n // can be a source path or device.\n public var source: String\n // Target specifies an optional subdirectory as a mountpoint.\n public var target: String\n // Options contains zero or more fstab-style mount options.\n public var options: [String]\n\n public init(type: String, source: String, target: String, options: [String]) {\n self.type = type\n self.source = source\n self.target = target\n self.options = options\n }\n}\n\nextension Mount {\n internal struct FlagBehavior {\n let clear: Bool\n let flag: Int32\n\n public init(_ clear: Bool, _ flag: Int32) {\n self.clear = clear\n self.flag = flag\n }\n }\n\n #if os(Linux)\n internal static let flagsDictionary: [String: FlagBehavior] = [\n \"async\": .init(true, MS_SYNCHRONOUS),\n \"atime\": .init(true, MS_NOATIME),\n \"bind\": .init(false, MS_BIND),\n \"defaults\": .init(false, 0),\n \"dev\": .init(true, MS_NODEV),\n \"diratime\": .init(true, MS_NODIRATIME),\n \"dirsync\": .init(false, MS_DIRSYNC),\n \"exec\": .init(true, MS_NOEXEC),\n \"mand\": .init(false, MS_MANDLOCK),\n \"noatime\": .init(false, MS_NOATIME),\n \"nodev\": .init(false, MS_NODEV),\n \"nodiratime\": .init(false, MS_NODIRATIME),\n \"noexec\": .init(false, MS_NOEXEC),\n \"nomand\": .init(true, MS_MANDLOCK),\n \"norelatime\": .init(true, MS_RELATIME),\n \"nostrictatime\": .init(true, MS_STRICTATIME),\n \"nosuid\": .init(false, MS_NOSUID),\n \"rbind\": .init(false, MS_BIND | MS_REC),\n \"relatime\": .init(false, MS_RELATIME),\n \"remount\": .init(false, MS_REMOUNT),\n \"ro\": .init(false, MS_RDONLY),\n \"rw\": .init(true, MS_RDONLY),\n \"strictatime\": .init(false, MS_STRICTATIME),\n \"suid\": .init(true, MS_NOSUID),\n \"sync\": .init(false, MS_SYNCHRONOUS),\n ]\n\n internal struct MountOptions {\n var flags: Int32\n var data: [String]\n\n public init(_ flags: Int32 = 0, data: [String] = []) {\n self.flags = flags\n self.data = data\n }\n }\n\n /// Whether the mount is read only.\n public var readOnly: Bool {\n for option in self.options {\n if option == \"ro\" {\n return true\n }\n }\n return false\n }\n\n /// Mount the mount relative to `root` with the current set of data in the object.\n /// Optionally provide `createWithPerms` to set the permissions for the directory that\n /// it will be mounted at.\n public func mount(root: String, createWithPerms: Int16? = nil) throws {\n var rootURL = URL(fileURLWithPath: root)\n rootURL = rootURL.resolvingSymlinksInPath()\n rootURL = rootURL.appendingPathComponent(self.target)\n try self.mountToTarget(target: rootURL.path, createWithPerms: createWithPerms)\n }\n\n /// Mount the mount with the current set of data in the object. Optionally\n /// provide `createWithPerms` to set the permissions for the directory that\n /// it will be mounted at.\n public func mount(createWithPerms: Int16? = nil) throws {\n try self.mountToTarget(target: self.target, createWithPerms: createWithPerms)\n }\n\n private func mountToTarget(target: String, createWithPerms: Int16?) throws {\n let pageSize = sysconf(_SC_PAGESIZE)\n\n let opts = parseMountOptions()\n let dataString = opts.data.joined(separator: \",\")\n if dataString.count > pageSize {\n throw Error.validation(\"data string exceeds page size (\\(dataString.count) > \\(pageSize))\")\n }\n\n let propagationTypes: Int32 = MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE\n\n // Ensure propagation type change flags aren't included in other calls.\n let originalFlags = opts.flags & ~(propagationTypes)\n\n let targetURL = URL(fileURLWithPath: self.target)\n let targetParent = targetURL.deletingLastPathComponent().path\n if let perms = createWithPerms {\n try mkdirAll(targetParent, perms)\n }\n try mkdirAll(target, 0o755)\n\n if opts.flags & MS_REMOUNT == 0 || !dataString.isEmpty {\n guard _mount(self.source, target, self.type, UInt(originalFlags), dataString) == 0 else {\n throw Error.errno(\n errno,\n \"failed initial mount source=\\(self.source) target=\\(target) type=\\(self.type) data=\\(dataString)\"\n )\n }\n }\n\n if opts.flags & propagationTypes != 0 {\n // Change the propagation type.\n let pflags = propagationTypes | MS_REC | MS_SILENT\n guard _mount(\"\", target, \"\", UInt(opts.flags & pflags), \"\") == 0 else {\n throw Error.errno(errno, \"failed propagation change mount\")\n }\n }\n\n let bindReadOnlyFlags = MS_BIND | MS_RDONLY\n if originalFlags & bindReadOnlyFlags == bindReadOnlyFlags {\n guard _mount(\"\", target, \"\", UInt(originalFlags | MS_REMOUNT), \"\") == 0 else {\n throw Error.errno(errno, \"failed bind mount\")\n }\n }\n }\n\n private func mkdirAll(_ name: String, _ perm: Int16) throws {\n try FileManager.default.createDirectory(\n atPath: name,\n withIntermediateDirectories: true,\n attributes: [.posixPermissions: perm]\n )\n }\n\n private func parseMountOptions() -> MountOptions {\n var mountOpts = MountOptions()\n for option in self.options {\n if let entry = Self.flagsDictionary[option], entry.flag != 0 {\n if entry.clear {\n mountOpts.flags &= ~entry.flag\n } else {\n mountOpts.flags |= entry.flag\n }\n } else {\n mountOpts.data.append(option)\n }\n }\n return mountOpts\n }\n\n /// `Mount` errors\n public enum Error: Swift.Error, CustomStringConvertible {\n case errno(Int32, String)\n case validation(String)\n\n public var description: String {\n switch self {\n case .errno(let errno, let message):\n return \"mount failed with errno \\(errno): \\(message)\"\n case .validation(let message):\n return \"failed during validation: \\(message)\"\n }\n }\n }\n #endif\n}\n"], ["/containerization/vminitd/Sources/vmexec/RunCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerizationOCI\nimport Foundation\nimport LCShim\nimport Logging\nimport Musl\n\nstruct RunCommand: ParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"run\",\n abstract: \"Run a container\"\n )\n\n @Option(name: .long, help: \"path to an OCI bundle\")\n var bundlePath: String\n\n mutating func run() throws {\n LoggingSystem.bootstrap(App.standardError)\n let log = Logger(label: \"vmexec\")\n\n let bundle = try ContainerizationOCI.Bundle.load(path: URL(filePath: bundlePath))\n let ociSpec = try bundle.loadConfig()\n try execInNamespace(spec: ociSpec, log: log)\n }\n\n private func childRootSetup(rootfs: ContainerizationOCI.Root, mounts: [ContainerizationOCI.Mount], log: Logger) throws {\n // setup rootfs\n try prepareRoot(rootfs: rootfs.path)\n try mountRootfs(rootfs: rootfs.path, mounts: mounts)\n try setDevSymlinks(rootfs: rootfs.path)\n\n try pivotRoot(rootfs: rootfs.path)\n try reOpenDevNull()\n }\n\n private func execInNamespace(spec: ContainerizationOCI.Spec, log: Logger) throws {\n guard let process = spec.process else {\n fatalError(\"no process configuration found in runtime spec\")\n }\n guard let root = spec.root else {\n fatalError(\"no root found in runtime spec\")\n }\n\n let syncfd = FileHandle(fileDescriptor: 3)\n if fcntl(3, F_SETFD, FD_CLOEXEC) == -1 {\n throw App.Errno(stage: \"cloexec(syncfd)\")\n }\n\n guard unshare(CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWUTS) == 0 else {\n throw App.Errno(stage: \"unshare(pid|mnt|uts)\")\n }\n\n let childPipe = Pipe()\n try childPipe.setCloexec()\n let processID = fork()\n\n guard processID != -1 else {\n try? childPipe.fileHandleForReading.close()\n try? childPipe.fileHandleForWriting.close()\n try? syncfd.close()\n\n throw App.Errno(stage: \"fork\")\n }\n\n if processID == 0 { // child\n try childPipe.fileHandleForReading.close()\n try syncfd.close()\n\n guard unshare(CLONE_NEWCGROUP) == 0 else {\n throw App.Errno(stage: \"unshare(cgroup)\")\n }\n\n guard setsid() != -1 else {\n throw App.Errno(stage: \"setsid()\")\n }\n\n try childRootSetup(rootfs: root, mounts: spec.mounts, log: log)\n\n if !spec.hostname.isEmpty {\n let errCode = spec.hostname.withCString { ptr in\n Musl.sethostname(ptr, spec.hostname.count)\n }\n guard errCode == 0 else {\n throw App.Errno(stage: \"sethostname()\")\n }\n }\n\n // Apply O_CLOEXEC to all file descriptors except stdio.\n // This ensures that all unwanted fds we may have accidentally\n // inherited are marked close-on-exec so they stay out of the\n // container.\n try App.applyCloseExecOnFDs()\n\n try App.setRLimits(rlimits: process.rlimits)\n\n // Change stdio to be owned by the requested user.\n try App.fixStdioPerms(user: process.user)\n\n // Set uid, gid, and supplementary groups.\n try App.setPermissions(user: process.user)\n\n if process.terminal {\n guard ioctl(0, UInt(TIOCSCTTY), 0) != -1 else {\n throw App.Errno(stage: \"setctty()\")\n }\n }\n\n try App.exec(process: process)\n } else { // parent process\n try childPipe.fileHandleForWriting.close()\n\n // wait until the pipe is closed then carry on.\n _ = try childPipe.fileHandleForReading.readToEnd()\n try childPipe.fileHandleForReading.close()\n\n // send our child's pid to our parent before we exit.\n var childPid = processID\n let data = Data(bytes: &childPid, count: MemoryLayout.size(ofValue: childPid))\n\n try syncfd.write(contentsOf: data)\n try syncfd.close()\n }\n }\n\n private func mountRootfs(rootfs: String, mounts: [ContainerizationOCI.Mount]) throws {\n let containerMount = ContainerMount(rootfs: rootfs, mounts: mounts)\n try containerMount.mountToRootfs()\n try containerMount.configureConsole()\n }\n\n private func prepareRoot(rootfs: String) throws {\n guard mount(\"\", \"/\", \"\", UInt(MS_SLAVE | MS_REC), nil) == 0 else {\n throw App.Errno(stage: \"mount(slave|rec)\")\n }\n\n guard mount(rootfs, rootfs, \"bind\", UInt(MS_BIND | MS_REC), nil) == 0 else {\n throw App.Errno(stage: \"mount(bind|rec)\")\n }\n }\n\n private func setDevSymlinks(rootfs: String) throws {\n let links: [(src: String, dst: String)] = [\n (\"/proc/self/fd\", \"/dev/fd\"),\n (\"/proc/self/fd/0\", \"/dev/stdin\"),\n (\"/proc/self/fd/1\", \"/dev/stdout\"),\n (\"/proc/self/fd/2\", \"/dev/stderr\"),\n ]\n\n let rootfsURL = URL(fileURLWithPath: rootfs)\n for (src, dst) in links {\n let dest = rootfsURL.appendingPathComponent(dst)\n guard symlink(src, dest.path) == 0 else {\n if errno == EEXIST {\n continue\n }\n throw App.Errno(stage: \"symlink()\")\n }\n }\n }\n\n private func reOpenDevNull() throws {\n let file = open(\"/dev/null\", O_RDWR)\n guard file != -1 else {\n throw App.Errno(stage: \"open(/dev/null)\")\n }\n defer { close(file) }\n\n var devNullStat = stat()\n try withUnsafeMutablePointer(to: &devNullStat) { pointer in\n guard fstat(file, pointer) == 0 else {\n throw App.Errno(stage: \"fstat(/dev/null)\")\n }\n }\n\n for fd: Int32 in 0...2 {\n var fdStat = stat()\n try withUnsafeMutablePointer(to: &fdStat) { pointer in\n guard fstat(fd, pointer) == 0 else {\n throw App.Errno(stage: \"fstat(fd)\")\n }\n }\n\n if fdStat.st_rdev == devNullStat.st_rdev {\n guard dup3(file, fd, 0) != -1 else {\n throw App.Errno(stage: \"dup3(null)\")\n }\n }\n }\n }\n\n /// Pivots the rootfs of the calling process in the namespace to the provided\n /// rootfs in the argument.\n ///\n /// The pivot_root(\".\", \".\") and unmount old root approach is exactly the same\n /// as runc's pivot root implementation in:\n /// https://github.com/opencontainers/runc/blob/main/libcontainer/rootfs_linux.go\n private func pivotRoot(rootfs: String) throws {\n let oldRoot = open(\"/\", O_RDONLY | O_DIRECTORY)\n if oldRoot <= 0 {\n throw App.Errno(stage: \"open(oldroot)\")\n }\n defer { close(oldRoot) }\n\n let newRoot = open(rootfs, O_RDONLY | O_DIRECTORY)\n if newRoot <= 0 {\n throw App.Errno(stage: \"open(newroot)\")\n }\n\n defer { close(newRoot) }\n\n // change cwd to the new root\n guard fchdir(newRoot) == 0 else {\n throw App.Errno(stage: \"fchdir(newroot)\")\n }\n guard CZ_pivot_root(toCString(\".\"), toCString(\".\")) == 0 else {\n throw App.Errno(stage: \"pivot_root()\")\n }\n // change cwd to the old root\n guard fchdir(oldRoot) == 0 else {\n throw App.Errno(stage: \"fchdir(oldroot)\")\n }\n // mount old root rslave so that unmount doesn't propagate back to outside\n // the namespace\n guard mount(\"\", \".\", \"\", UInt(MS_SLAVE | MS_REC), nil) == 0 else {\n throw App.Errno(stage: \"mount(., slave|rec)\")\n }\n // unmount old root\n guard umount2(\".\", Int32(MNT_DETACH)) == 0 else {\n throw App.Errno(stage: \"umount(.)\")\n }\n // switch cwd to the new root\n guard chdir(\"/\") == 0 else {\n throw App.Errno(stage: \"chdir(/)\")\n }\n }\n\n private func toCString(_ str: String) -> UnsafeMutablePointer? {\n let cString = str.utf8CString\n let cStringCopy = UnsafeMutableBufferPointer.allocate(capacity: cString.count)\n _ = cStringCopy.initialize(from: cString)\n return UnsafeMutablePointer(cStringCopy.baseAddress)\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/Formatter+Unpack.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport ContainerizationArchive\nimport Foundation\nimport ContainerizationOS\nimport SystemPackage\nimport ContainerizationExtras\n\nprivate typealias Hardlinks = [FilePath: FilePath]\n\nextension EXT4.Formatter {\n /// Unpack the provided archive on to the ext4 filesystem.\n public func unpack(reader: ArchiveReader, progress: ProgressHandler? = nil) throws {\n var hardlinks: Hardlinks = [:]\n for (entry, data) in reader {\n try Task.checkCancellation()\n guard var pathEntry = entry.path else {\n continue\n }\n\n defer {\n // Count the number of entries\n if let progress {\n Task {\n await progress([\n ProgressEvent(event: \"add-items\", value: 1)\n ])\n }\n }\n }\n\n pathEntry = preProcessPath(s: pathEntry)\n let path = FilePath(pathEntry)\n\n if path.base.hasPrefix(\".wh.\") {\n if path.base == \".wh..wh..opq\" { // whiteout directory\n try self.unlink(path: path.dir, directoryWhiteout: true)\n continue\n }\n let startIndex = path.base.index(path.base.startIndex, offsetBy: \".wh.\".count)\n let filePath = String(path.base[startIndex...])\n let dir: FilePath = path.dir\n try self.unlink(path: dir.join(filePath))\n continue\n }\n\n if let hardlink = entry.hardlink {\n let hl = preProcessPath(s: hardlink)\n hardlinks[path] = FilePath(hl)\n continue\n }\n let ts = FileTimestamps(\n access: entry.contentAccessDate, modification: entry.modificationDate, creation: entry.creationDate)\n switch entry.fileType {\n case .directory:\n try self.create(\n path: path, mode: EXT4.Inode.Mode(.S_IFDIR, entry.permissions), ts: ts, uid: entry.owner,\n gid: entry.group,\n xattrs: entry.xattrs)\n case .regular:\n let inputStream = InputStream(data: data)\n inputStream.open()\n try self.create(\n path: path, mode: EXT4.Inode.Mode(.S_IFREG, entry.permissions), ts: ts, buf: inputStream,\n uid: entry.owner,\n gid: entry.group, xattrs: entry.xattrs)\n inputStream.close()\n\n // Count the size of files\n if let progress {\n Task {\n let size = Int64(data.count)\n await progress([\n ProgressEvent(event: \"add-size\", value: size)\n ])\n }\n }\n case .symbolicLink:\n var symlinkTarget: FilePath?\n if let target = entry.symlinkTarget {\n symlinkTarget = FilePath(target)\n }\n try self.create(\n path: path, link: symlinkTarget, mode: EXT4.Inode.Mode(.S_IFLNK, entry.permissions), ts: ts,\n uid: entry.owner,\n gid: entry.group, xattrs: entry.xattrs)\n default:\n continue\n }\n }\n guard hardlinks.acyclic else {\n throw UnpackError.circularLinks\n }\n for (path, _) in hardlinks {\n if let resolvedTarget = try hardlinks.resolve(path) {\n try self.link(link: path, target: resolvedTarget)\n }\n }\n }\n\n /// Unpack an archive at the source URL on to the ext4 filesystem.\n public func unpack(\n source: URL,\n format: ContainerizationArchive.Format = .paxRestricted,\n compression: ContainerizationArchive.Filter = .gzip,\n progress: ProgressHandler? = nil\n ) throws {\n let reader = try ArchiveReader(\n format: format,\n filter: compression,\n file: source\n )\n try self.unpack(reader: reader, progress: progress)\n }\n\n private func preProcessPath(s: String) -> String {\n var p = s\n if p.hasPrefix(\"./\") {\n p = String(p.dropFirst())\n }\n if !p.hasPrefix(\"/\") {\n p = \"/\" + p\n }\n return p\n }\n}\n\n/// Common errors for unpacking an archive onto an ext4 filesystem.\npublic enum UnpackError: Swift.Error, CustomStringConvertible, Sendable, Equatable {\n /// The name is invalid.\n case invalidName(_ name: String)\n /// A circular link is found.\n case circularLinks\n\n /// The description of the error.\n public var description: String {\n switch self {\n case .invalidName(let name):\n return \"'\\(name)' is an invalid name\"\n case .circularLinks:\n return \"circular links found\"\n }\n }\n}\n\nextension Hardlinks {\n fileprivate var acyclic: Bool {\n for (_, target) in self {\n var visited: Set = [target]\n var next = target\n while let item = self[next] {\n if visited.contains(item) {\n return false\n }\n next = item\n visited.insert(next)\n }\n }\n return true\n }\n\n fileprivate func resolve(_ key: FilePath) throws -> FilePath? {\n let target = self[key]\n guard let target else {\n return nil\n }\n var next = target\n let visited: Set = [next]\n while let item = self[next] {\n if visited.contains(item) {\n throw UnpackError.circularLinks\n }\n next = item\n }\n return next\n }\n}\n#endif\n"], ["/containerization/vminitd/Sources/vminitd/IOPair.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOS\nimport Foundation\nimport Logging\nimport Synchronization\n\nfinal class IOPair: Sendable {\n let readFrom: IOCloser\n let writeTo: IOCloser\n nonisolated(unsafe) let buffer: UnsafeMutableBufferPointer\n private let logger: Logger?\n\n private let done: Atomic\n\n init(readFrom: IOCloser, writeTo: IOCloser, logger: Logger? = nil) {\n self.readFrom = readFrom\n self.writeTo = writeTo\n self.done = Atomic(false)\n self.buffer = UnsafeMutableBufferPointer.allocate(capacity: Int(getpagesize()))\n self.logger = logger\n }\n\n func relay() throws {\n let readFromFd = self.readFrom.fileDescriptor\n let writeToFd = self.writeTo.fileDescriptor\n\n let readFrom = OSFile(fd: readFromFd)\n let writeTo = OSFile(fd: writeToFd)\n\n try ProcessSupervisor.default.poller.add(readFromFd, mask: EPOLLIN) { mask in\n if mask.isHangup && !mask.readyToRead {\n self.close()\n return\n }\n // Loop so that in the case that someone wrote > buf.count down the pipe\n // we properly will drain it fully.\n while true {\n let r = readFrom.read(self.buffer)\n if r.read > 0 {\n let view = UnsafeMutableBufferPointer(\n start: self.buffer.baseAddress,\n count: r.read\n )\n\n let w = writeTo.write(view)\n if w.wrote != r.read {\n self.logger?.error(\"stopping relay: short write for stdio\")\n self.close()\n return\n }\n }\n\n switch r.action {\n case .error(let errno):\n self.logger?.error(\"failed with errno \\(errno) while reading for fd \\(readFromFd)\")\n fallthrough\n case .eof:\n self.close()\n self.logger?.debug(\"closing relay for \\(readFromFd)\")\n return\n case .again:\n // We read all we could, exit.\n if mask.isHangup {\n self.close()\n }\n return\n default:\n break\n }\n }\n }\n }\n\n func close() {\n guard\n self.done.compareExchange(\n expected: false,\n desired: true,\n successOrdering: .acquiringAndReleasing,\n failureOrdering: .acquiring\n ).exchanged\n else {\n return\n }\n\n self.buffer.deallocate()\n\n let readFromFd = self.readFrom.fileDescriptor\n // Remove the fd from our global epoll instance first.\n do {\n try ProcessSupervisor.default.poller.delete(readFromFd)\n } catch {\n self.logger?.error(\"failed to delete fd from epoll \\(readFromFd): \\(error)\")\n }\n\n do {\n try self.readFrom.close()\n } catch {\n self.logger?.error(\"failed to close reader fd for IOPair: \\(error)\")\n }\n\n do {\n try self.writeTo.close()\n } catch {\n self.logger?.error(\"failed to close writer fd for IOPair: \\(error)\")\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/LocalOCILayoutClient.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport Crypto\nimport Foundation\nimport NIOCore\nimport NIOFoundationCompat\n\npackage final class LocalOCILayoutClient: ContentClient {\n let cs: LocalContentStore\n\n package init(root: URL) throws {\n self.cs = try LocalContentStore(path: root)\n }\n\n private func _fetch(digest: String) async throws -> Content {\n guard let c: Content = try await self.cs.get(digest: digest) else {\n throw Error.missingContent(digest)\n }\n return c\n }\n\n package func fetch(name: String, descriptor: Descriptor) async throws -> T {\n let c = try await self._fetch(digest: descriptor.digest)\n return try c.decode()\n }\n\n package func fetchBlob(name: String, descriptor: Descriptor, into file: URL, progress: ProgressHandler?) async throws -> (Int64, SHA256Digest) {\n let c = try await self._fetch(digest: descriptor.digest)\n let fileManager = FileManager.default\n let filePath = file.absolutePath()\n if !fileManager.fileExists(atPath: filePath) {\n let src = c.path\n try fileManager.copyItem(at: src, to: file)\n\n if let progress, let fileSize = fileManager.fileSize(atPath: filePath) {\n await progress([\n ProgressEvent(event: \"add-size\", value: fileSize)\n ])\n }\n }\n let size = try Int64(c.size())\n let digest = try c.digest()\n return (size, digest)\n }\n\n package func fetchData(name: String, descriptor: Descriptor) async throws -> Data {\n let c = try await self._fetch(digest: descriptor.digest)\n return try c.data()\n }\n\n package func push(\n name: String,\n ref: String,\n descriptor: Descriptor,\n streamGenerator: () throws -> T,\n progress: ProgressHandler?\n ) async throws where T.Element == ByteBuffer {\n let input = try streamGenerator()\n\n let (id, dir) = try await self.cs.newIngestSession()\n do {\n let into = dir.appendingPathComponent(descriptor.digest.trimmingDigestPrefix)\n guard FileManager.default.createFile(atPath: into.path, contents: nil) else {\n throw Error.cannotCreateFile\n }\n let fd = try FileHandle(forWritingTo: into)\n defer {\n try? fd.close()\n }\n var wrote = 0\n var hasher = SHA256()\n\n for try await buffer in input {\n wrote += buffer.readableBytes\n try fd.write(contentsOf: buffer.readableBytesView)\n hasher.update(data: buffer.readableBytesView)\n }\n try await self.cs.completeIngestSession(id)\n } catch {\n try await self.cs.cancelIngestSession(id)\n }\n }\n}\n\nextension LocalOCILayoutClient {\n private static let ociLayoutFileName = \"oci-layout\"\n private static let ociLayoutVersionString = \"imageLayoutVersion\"\n private static let ociLayoutIndexFileName = \"index.json\"\n\n package func loadIndexFromOCILayout(directory: URL) throws -> ContainerizationOCI.Index {\n let fm = FileManager.default\n let decoder = JSONDecoder()\n\n let ociLayoutFile = directory.appendingPathComponent(Self.ociLayoutFileName)\n guard fm.fileExists(atPath: ociLayoutFile.absolutePath()) else {\n throw ContainerizationError(.notFound, message: ociLayoutFile.absolutePath())\n }\n var data = try Data(contentsOf: ociLayoutFile)\n let ociLayout = try decoder.decode([String: String].self, from: data)\n guard ociLayout[Self.ociLayoutVersionString] != nil else {\n throw ContainerizationError(.empty, message: \"missing key \\(Self.ociLayoutVersionString) in \\(ociLayoutFile.absolutePath())\")\n }\n\n let indexFile = directory.appendingPathComponent(Self.ociLayoutIndexFileName)\n guard fm.fileExists(atPath: indexFile.absolutePath()) else {\n throw ContainerizationError(.notFound, message: indexFile.absolutePath())\n }\n data = try Data(contentsOf: indexFile)\n let index = try decoder.decode(ContainerizationOCI.Index.self, from: data)\n return index\n }\n\n package func createOCILayoutStructure(directory: URL, manifests: [Descriptor]) throws {\n let fm = FileManager.default\n let encoder = JSONEncoder()\n encoder.outputFormatting = [.withoutEscapingSlashes]\n\n let ingestDir = directory.appendingPathComponent(\"ingest\")\n try? fm.removeItem(at: ingestDir)\n let ociLayoutContent: [String: String] = [\n Self.ociLayoutVersionString: \"1.0.0\"\n ]\n\n var data = try encoder.encode(ociLayoutContent)\n var p = directory.appendingPathComponent(Self.ociLayoutFileName).absolutePath()\n guard fm.createFile(atPath: p, contents: data) else {\n throw ContainerizationError(.internalError, message: \"failed to create file \\(p)\")\n }\n let idx = ContainerizationOCI.Index(schemaVersion: 2, manifests: manifests)\n data = try encoder.encode(idx)\n p = directory.appendingPathComponent(Self.ociLayoutIndexFileName).absolutePath()\n guard fm.createFile(atPath: p, contents: data) else {\n throw ContainerizationError(.internalError, message: \"failed to create file \\(p)\")\n }\n }\n\n package func setImageReferenceAnnotation(descriptor: inout Descriptor, reference: String) {\n var annotations = descriptor.annotations ?? [:]\n annotations[AnnotationKeys.containerizationImageName] = reference\n annotations[AnnotationKeys.containerdImageName] = reference\n annotations[AnnotationKeys.openContainersImageName] = reference\n descriptor.annotations = annotations\n }\n\n package func getImageReferencefromDescriptor(descriptor: Descriptor) -> String? {\n let annotations = descriptor.annotations\n guard let annotations else {\n return nil\n }\n\n // Annotations here do not conform to the OCI image specification.\n // The interpretation of the annotations \"org.opencontainers.image.ref.name\" and\n // \"io.containerd.image.name\" is under debate:\n // - OCI spec examples suggest it should be the image tag:\n // https://github.com/opencontainers/image-spec/blob/fbb4662eb53b80bd38f7597406cf1211317768f0/image-layout.md?plain=1#L175\n // - Buildkitd maintainers argue it should represent the full image name:\n // https://github.com/moby/buildkit/issues/4615#issuecomment-2521810830\n // Until a consensus is reached, the preference is given to \"com.apple.containerization.image.name\" and then to\n // using \"io.containerd.image.name\" as it is the next safest choice\n if let name = annotations[AnnotationKeys.containerizationImageName] {\n return name\n }\n if let name = annotations[AnnotationKeys.containerdImageName] {\n return name\n }\n if let name = annotations[AnnotationKeys.openContainersImageName] {\n return name\n }\n return nil\n }\n\n package enum Error: Swift.Error {\n case missingContent(_ digest: String)\n case unsupportedInput\n case cannotCreateFile\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/ManagedContainer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nactor ManagedContainer {\n let id: String\n let initProcess: ManagedProcess\n\n private let _log: Logger\n private let _bundle: ContainerizationOCI.Bundle\n private var _execs: [String: ManagedProcess] = [:]\n\n var pid: Int32 {\n self.initProcess.pid\n }\n\n init(\n id: String,\n stdio: HostStdio,\n spec: ContainerizationOCI.Spec,\n log: Logger\n ) throws {\n let bundle = try ContainerizationOCI.Bundle.create(\n path: Self.craftBundlePath(id: id),\n spec: spec\n )\n log.info(\"created bundle with spec \\(spec)\")\n\n let initProcess = try ManagedProcess(\n id: id,\n stdio: stdio,\n bundle: bundle,\n owningPid: nil,\n log: log\n )\n log.info(\"created managed init process\")\n\n self.initProcess = initProcess\n self.id = id\n self._bundle = bundle\n self._log = log\n }\n}\n\nextension ManagedContainer {\n private func ensureExecExists(_ id: String) throws {\n if self._execs[id] == nil {\n throw ContainerizationError(\n .invalidState,\n message: \"exec \\(id) does not exist in container \\(self.id)\"\n )\n }\n }\n\n func createExec(\n id: String,\n stdio: HostStdio,\n process: ContainerizationOCI.Process\n ) throws {\n // Write the process config to the bundle, and pass this on\n // over to ManagedProcess to deal with.\n try self._bundle.createExecSpec(\n id: id,\n process: process\n )\n let process = try ManagedProcess(\n id: id,\n stdio: stdio,\n bundle: self._bundle,\n owningPid: self.initProcess.pid,\n log: self._log\n )\n self._execs[id] = process\n }\n\n func start(execID: String) async throws -> Int32 {\n let proc = try self.getExecOrInit(execID: execID)\n return try await ProcessSupervisor.default.start(process: proc)\n }\n\n func wait(execID: String) async throws -> Int32 {\n let proc = try self.getExecOrInit(execID: execID)\n return await proc.wait()\n }\n\n func kill(execID: String, _ signal: Int32) throws {\n let proc = try self.getExecOrInit(execID: execID)\n try proc.kill(signal)\n }\n\n func resize(execID: String, size: Terminal.Size) throws {\n let proc = try self.getExecOrInit(execID: execID)\n try proc.resize(size: size)\n }\n\n func closeStdin(execID: String) throws {\n let proc = try self.getExecOrInit(execID: execID)\n try proc.closeStdin()\n }\n\n func deleteExec(id: String) throws {\n try ensureExecExists(id)\n do {\n try self._bundle.deleteExecSpec(id: id)\n } catch {\n self._log.error(\"failed to remove exec spec from filesystem: \\(error)\")\n }\n self._execs.removeValue(forKey: id)\n }\n\n func delete() throws {\n try self._bundle.delete()\n }\n\n func getExecOrInit(execID: String) throws -> ManagedProcess {\n if execID == self.id {\n return self.initProcess\n }\n guard let proc = self._execs[execID] else {\n throw ContainerizationError(\n .invalidState,\n message: \"exec \\(execID) does not exist in container \\(self.id)\"\n )\n }\n return proc\n }\n}\n\nextension ContainerizationOCI.Bundle {\n func createExecSpec(id: String, process: ContainerizationOCI.Process) throws {\n let specDir = self.path.appending(path: \"execs/\\(id)\")\n\n let fm = FileManager.default\n try fm.createDirectory(\n atPath: specDir.path,\n withIntermediateDirectories: true\n )\n\n let specData = try JSONEncoder().encode(process)\n let processConfigPath = specDir.appending(path: \"process.json\")\n try specData.write(to: processConfigPath)\n }\n\n func getExecSpecPath(id: String) -> URL {\n self.path.appending(path: \"execs/\\(id)/process.json\")\n }\n\n func deleteExecSpec(id: String) throws {\n let specDir = self.path.appending(path: \"execs/\\(id)\")\n\n let fm = FileManager.default\n try fm.removeItem(at: specDir)\n }\n}\n\nextension ManagedContainer {\n static func craftBundlePath(id: String) -> URL {\n URL(fileURLWithPath: \"/run/container\").appending(path: id)\n }\n}\n"], ["/containerization/Sources/Containerization/Image/ImageStore/ImageStore+Export.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n//\n\nimport ContainerizationError\nimport ContainerizationExtras\nimport ContainerizationIO\nimport ContainerizationOCI\nimport Crypto\nimport Foundation\n\nextension ImageStore {\n internal struct ExportOperation {\n let name: String\n let tag: String\n let contentStore: ContentStore\n let client: ContentClient\n let progress: ProgressHandler?\n\n init(name: String, tag: String, contentStore: ContentStore, client: ContentClient, progress: ProgressHandler? = nil) {\n self.contentStore = contentStore\n self.client = client\n self.progress = progress\n self.name = name\n self.tag = tag\n }\n\n @discardableResult\n internal func export(index: Descriptor, platforms: (Platform) -> Bool) async throws -> Descriptor {\n var pushQueue: [[Descriptor]] = []\n var current: [Descriptor] = [index]\n while !current.isEmpty {\n let children = try await self.getChildren(descs: current)\n let matches = try filterPlatforms(matcher: platforms, children).uniqued { $0.digest }\n pushQueue.append(matches)\n current = matches\n }\n let localIndexData = try await self.createIndex(from: index, matching: platforms)\n\n await updatePushProgress(pushQueue: pushQueue, localIndexData: localIndexData)\n\n // We need to work bottom up when pushing an image.\n // First, the tar blobs / config layers, then, the manifests and so on...\n // When processing a given \"level\", the requests maybe made in parallel.\n // We need to ensure that the child level has been uploaded fully\n // before uploading the parent level.\n try await withThrowingTaskGroup(of: Void.self) { group in\n for layerGroup in pushQueue.reversed() {\n for chunk in layerGroup.chunks(ofCount: 8) {\n for desc in chunk {\n guard let content = try await self.contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(desc.digest)\")\n }\n group.addTask {\n let readStream = try ReadStream(url: content.path)\n try await self.pushContent(descriptor: desc, stream: readStream)\n }\n }\n try await group.waitForAll()\n }\n }\n }\n\n // Lastly, we need to construct and push a new index, since we may\n // have pushed content only for specific platforms.\n let digest = SHA256.hash(data: localIndexData)\n let descriptor = Descriptor(\n mediaType: MediaTypes.index,\n digest: digest.digestString,\n size: Int64(localIndexData.count))\n let stream = ReadStream(data: localIndexData)\n try await self.pushContent(descriptor: descriptor, stream: stream)\n return descriptor\n }\n\n private func updatePushProgress(pushQueue: [[Descriptor]], localIndexData: Data) async {\n for layerGroup in pushQueue {\n for desc in layerGroup {\n await progress?([\n ProgressEvent(event: \"add-total-size\", value: desc.size),\n ProgressEvent(event: \"add-total-items\", value: 1),\n ])\n }\n }\n await progress?([\n ProgressEvent(event: \"add-total-size\", value: localIndexData.count),\n ProgressEvent(event: \"add-total-items\", value: 1),\n ])\n }\n\n private func createIndex(from index: Descriptor, matching: (Platform) -> Bool) async throws -> Data {\n guard let content = try await self.contentStore.get(digest: index.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(index.digest)\")\n }\n var idx: Index = try content.decode()\n let manifests = idx.manifests\n var matchedManifests: [Descriptor] = []\n var skippedPlatforms = false\n for manifest in manifests {\n guard let p = manifest.platform else {\n continue\n }\n if matching(p) {\n matchedManifests.append(manifest)\n } else {\n skippedPlatforms = true\n }\n }\n if !skippedPlatforms {\n return try content.data()\n }\n idx.manifests = matchedManifests\n return try JSONEncoder().encode(idx)\n }\n\n private func pushContent(descriptor: Descriptor, stream: ReadStream) async throws {\n do {\n let generator = {\n try stream.reset()\n return stream.stream\n }\n try await client.push(name: name, ref: tag, descriptor: descriptor, streamGenerator: generator, progress: progress)\n await progress?([\n ProgressEvent(event: \"add-size\", value: descriptor.size),\n ProgressEvent(event: \"add-items\", value: 1),\n ])\n } catch let err as ContainerizationError {\n guard err.code != .exists else {\n // We reported the total items and size and have to account for them in existing content.\n await progress?([\n ProgressEvent(event: \"add-size\", value: descriptor.size),\n ProgressEvent(event: \"add-items\", value: 1),\n ])\n return\n }\n throw err\n }\n }\n\n private func getChildren(descs: [Descriptor]) async throws -> [Descriptor] {\n var out: [Descriptor] = []\n for desc in descs {\n let mediaType = desc.mediaType\n guard let content = try await self.contentStore.get(digest: desc.digest) else {\n throw ContainerizationError(.notFound, message: \"Content with digest \\(desc.digest)\")\n }\n switch mediaType {\n case MediaTypes.index, MediaTypes.dockerManifestList:\n let index: Index = try content.decode()\n out.append(contentsOf: index.manifests)\n case MediaTypes.imageManifest, MediaTypes.dockerManifest:\n let manifest: Manifest = try content.decode()\n out.append(manifest.config)\n out.append(contentsOf: manifest.layers)\n default:\n continue\n }\n }\n return out\n }\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/OSFile.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nstruct OSFile: Sendable {\n private let fd: Int32\n\n enum IOAction: Equatable {\n case eof\n case again\n case success\n case brokenPipe\n case error(_ errno: Int32)\n }\n\n var closed: Bool {\n Foundation.fcntl(fd, F_GETFD) == -1 && errno == EBADF\n }\n\n var fileDescriptor: Int32 { fd }\n\n init(fd: Int32) {\n self.fd = fd\n }\n\n init(handle: FileHandle) {\n self.fd = handle.fileDescriptor\n }\n\n func close() throws {\n guard Foundation.close(self.fd) == 0 else {\n throw POSIXError(.init(rawValue: errno)!)\n }\n }\n\n func read(_ buffer: UnsafeMutableBufferPointer) -> (read: Int, action: IOAction) {\n if buffer.count == 0 {\n return (0, .success)\n }\n\n var bytesRead: Int = 0\n while true {\n let n = Foundation.read(\n self.fd,\n buffer.baseAddress!.advanced(by: bytesRead),\n buffer.count - bytesRead\n )\n if n == -1 {\n if errno == EAGAIN || errno == EIO {\n return (bytesRead, .again)\n }\n return (bytesRead, .error(errno))\n }\n\n if n == 0 {\n return (bytesRead, .eof)\n }\n\n bytesRead += n\n if bytesRead < buffer.count {\n continue\n }\n return (bytesRead, .success)\n }\n }\n\n func write(_ buffer: UnsafeMutableBufferPointer) -> (wrote: Int, action: IOAction) {\n if buffer.count == 0 {\n return (0, .success)\n }\n\n var bytesWrote: Int = 0\n while true {\n let n = Foundation.write(\n self.fd,\n buffer.baseAddress!.advanced(by: bytesWrote),\n buffer.count - bytesWrote\n )\n if n == -1 {\n if errno == EAGAIN || errno == EIO {\n return (bytesWrote, .again)\n }\n return (bytesWrote, .error(errno))\n }\n\n if n == 0 {\n return (bytesWrote, .brokenPipe)\n }\n\n bytesWrote += n\n if bytesWrote < buffer.count {\n continue\n }\n return (bytesWrote, .success)\n }\n }\n\n static func pipe() -> (read: Self, write: Self) {\n let pipe = Pipe()\n return (Self(handle: pipe.fileHandleForReading), Self(handle: pipe.fileHandleForWriting))\n }\n\n static func open(path: String) throws -> Self {\n try open(path: path, mode: O_RDONLY | O_CLOEXEC)\n }\n\n static func open(path: String, mode: Int32) throws -> Self {\n let fd = Foundation.open(path, mode)\n if fd < 0 {\n throw POSIXError(.init(rawValue: errno)!)\n }\n return Self(fd: fd)\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Keychain/KeychainQuery.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\nimport Foundation\n\n/// Holds the result of a query to the keychain.\npublic struct KeychainQueryResult {\n public var account: String\n public var data: String\n public var modifiedDate: Date\n public var createdDate: Date\n}\n\n/// Type that facilitates interacting with the macOS keychain.\npublic struct KeychainQuery {\n public init() {}\n\n /// Save a value to the keychain.\n public func save(id: String, host: String, user: String, token: String) throws {\n if try exists(id: id, host: host) {\n try delete(id: id, host: host)\n }\n\n guard let tokenEncoded = token.data(using: String.Encoding.utf8) else {\n throw Self.Error.invalidTokenConversion\n }\n let query: [String: Any] = [\n kSecClass as String: kSecClassInternetPassword,\n kSecAttrSecurityDomain as String: id,\n kSecAttrServer as String: host,\n kSecAttrAccount as String: user,\n kSecValueData as String: tokenEncoded,\n kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock,\n kSecAttrSynchronizable as String: false,\n ]\n let status = SecItemAdd(query as CFDictionary, nil)\n guard status == errSecSuccess else { throw Self.Error.unhandledError(status: status) }\n }\n\n /// Delete a value from the keychain.\n public func delete(id: String, host: String) throws {\n let query: [String: Any] = [\n kSecClass as String: kSecClassInternetPassword,\n kSecAttrSecurityDomain as String: id,\n kSecAttrServer as String: host,\n kSecMatchLimit as String: kSecMatchLimitOne,\n ]\n let status = SecItemDelete(query as CFDictionary)\n guard status == errSecSuccess || status == errSecItemNotFound else {\n throw Self.Error.unhandledError(status: status)\n }\n }\n\n /// Retrieve a value from the keychain.\n public func get(id: String, host: String) throws -> KeychainQueryResult? {\n let query: [String: Any] = [\n kSecClass as String: kSecClassInternetPassword,\n kSecAttrSecurityDomain as String: id,\n kSecAttrServer as String: host,\n kSecReturnAttributes as String: true,\n kSecMatchLimit as String: kSecMatchLimitOne,\n kSecReturnData as String: true,\n ]\n var item: CFTypeRef?\n let status = SecItemCopyMatching(query as CFDictionary, &item)\n let exists = try isQuerySuccessful(status)\n if !exists {\n return nil\n }\n\n guard let fetched = item as? [String: Any] else {\n throw Self.Error.unexpectedDataFetched\n }\n guard let data = fetched[kSecValueData as String] as? Data else {\n throw Self.Error.keyNotPresent(key: kSecValueData as String)\n }\n guard let decodedData = String(data: data, encoding: String.Encoding.utf8) else {\n throw Self.Error.unexpectedDataFetched\n }\n guard let account = fetched[kSecAttrAccount as String] as? String else {\n throw Self.Error.keyNotPresent(key: kSecAttrAccount as String)\n }\n guard let modifiedDate = fetched[kSecAttrModificationDate as String] as? Date else {\n throw Self.Error.keyNotPresent(key: kSecAttrModificationDate as String)\n }\n guard let createdDate = fetched[kSecAttrCreationDate as String] as? Date else {\n throw Self.Error.keyNotPresent(key: kSecAttrCreationDate as String)\n }\n return KeychainQueryResult(\n account: account,\n data: decodedData,\n modifiedDate: modifiedDate,\n createdDate: createdDate\n )\n }\n\n private func isQuerySuccessful(_ status: Int32) throws -> Bool {\n guard status != errSecItemNotFound else {\n return false\n }\n guard status == errSecSuccess else {\n throw Self.Error.unhandledError(status: status)\n }\n return true\n }\n\n /// Check if a value exists in the keychain.\n public func exists(id: String, host: String) throws -> Bool {\n let query: [String: Any] = [\n kSecClass as String: kSecClassInternetPassword,\n kSecAttrSecurityDomain as String: id,\n kSecAttrServer as String: host,\n kSecReturnAttributes as String: true,\n kSecMatchLimit as String: kSecMatchLimitOne,\n kSecReturnData as String: false,\n ]\n\n let status = SecItemCopyMatching(query as CFDictionary, nil)\n return try isQuerySuccessful(status)\n }\n}\n\nextension KeychainQuery {\n public enum Error: Swift.Error {\n case unhandledError(status: Int32)\n case unexpectedDataFetched\n case keyNotPresent(key: String)\n case invalidTokenConversion\n }\n}\n#endif\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Xattrs.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/*\n * Note: Both the entries and values for the attributes need to occupy a size that is a multiple of 4,\n * meaning, in cases where the attribute name or value is less than not a multiple of 4, it is padded with 0\n * until it reaches that size.\n */\n\nextension EXT4 {\n public struct ExtendedAttribute {\n public static let prefixMap: [Int: String] = [\n 1: \"user.\",\n 2: \"system.posix_acl_access\",\n 3: \"system.posix_acl_default\",\n 4: \"trusted.\",\n 6: \"security.\",\n 7: \"system.\",\n 8: \"system.richacl\",\n ]\n\n let name: String\n let index: UInt8\n let value: [UInt8]\n\n var sizeValue: UInt32 {\n UInt32((value.count + 3) & ~3)\n }\n\n var sizeEntry: UInt32 {\n UInt32((name.count + 3) & ~3 + 16) // 16 bytes are needed to store other metadata for the xattr entry\n }\n\n var size: UInt32 {\n sizeEntry + sizeValue\n }\n\n var fullName: String {\n Self.decompressName(id: Int(index), suffix: name)\n }\n\n var hash: UInt32 {\n var hash: UInt32 = 0\n for char in name {\n hash = (hash << 5) ^ (hash >> 27) ^ UInt32(char.asciiValue!)\n }\n var i = 0\n while i + 3 < value.count {\n let s = value[i..> 16) ^ v\n i += 4\n }\n if value.count % 4 != 0 {\n let last = value.count & ~3\n var buff: [UInt8] = [0, 0, 0, 0]\n for (i, byte) in value[last...].enumerated() {\n buff[i] = byte\n }\n let v = UInt32(littleEndian: buff.withUnsafeBytes { $0.load(as: UInt32.self) })\n hash = (hash << 16) ^ (hash >> 16) ^ v\n }\n return hash\n }\n\n init(name: String, value: [UInt8]) {\n let compressed = Self.compressName(name)\n self.name = compressed.str\n self.index = compressed.id\n self.value = value\n }\n\n init(idx: UInt8, compressedName name: String, value: [UInt8]) {\n self.name = name\n self.index = idx\n self.value = value\n }\n\n // MARK: Class methods\n public static func compressName(_ name: String) -> (id: UInt8, str: String) {\n for (id, prefix) in prefixMap.sorted(by: { $1.1.count < $0.1.count }) where name.hasPrefix(prefix) {\n return (UInt8(id), String(name.dropFirst(prefix.count)))\n }\n return (0, name)\n }\n\n public static func decompressName(id: Int, suffix: String) -> String {\n guard let prefix = prefixMap[id] else {\n return suffix\n }\n return \"\\(prefix)\\(suffix)\"\n }\n }\n\n public struct FileXattrsState {\n private let inodeCapacity: UInt32\n private let blockCapacity: UInt32\n private let inode: UInt32 // the inode number for which we are tracking these xattrs\n\n var inlineAttributes: [ExtendedAttribute] = []\n var blockAttributes: [ExtendedAttribute] = []\n private var usedSizeInline: UInt32 = 0\n private var usedSizeBlock: UInt32 = 0\n\n private var inodeFreeBytes: UInt32 {\n self.inodeCapacity - EXT4.XattrInodeHeaderSize - usedSizeInline - 4 // need to have 4 null bytes b/w xattr entries and values\n }\n\n private var blockFreeBytes: UInt32 {\n self.blockCapacity - EXT4.XattrBlockHeaderSize - usedSizeBlock - 4\n }\n\n init(inode: UInt32, inodeXattrCapacity: UInt32, blockCapacity: UInt32) {\n self.inode = inode\n self.inodeCapacity = inodeXattrCapacity\n self.blockCapacity = blockCapacity\n }\n\n public mutating func add(_ attribute: ExtendedAttribute) throws {\n let size = attribute.size\n if size <= inodeFreeBytes {\n usedSizeInline += size\n inlineAttributes.append(attribute)\n return\n }\n if size <= blockFreeBytes {\n usedSizeBlock += size\n blockAttributes.append(attribute)\n return\n }\n throw Error.insufficientSpace(Int(self.inode))\n }\n\n public func writeInlineAttributes(buffer: inout [UInt8]) throws {\n var idx = 0\n withUnsafeLittleEndianBytes(\n of: EXT4.XAttrHeaderMagic,\n body: { bytes in\n for byte in bytes {\n buffer[idx] = byte\n idx += 1\n }\n })\n try Self.write(buffer: &buffer, attrs: self.inlineAttributes, start: UInt16(idx), delta: 0, inline: true)\n }\n\n public func writeBlockAttributes(buffer: inout [UInt8]) throws {\n var idx = 0\n for val in [EXT4.XAttrHeaderMagic, 1, 1] {\n withUnsafeLittleEndianBytes(\n of: UInt32(val),\n body: { bytes in\n for byte in bytes {\n buffer[idx] = byte\n idx += 1\n }\n })\n }\n while idx != 32 {\n buffer[idx] = 0\n idx += 1\n }\n var attributes = self.blockAttributes\n attributes.sort(by: {\n if ($0.index < $1.index) || ($0.name.count < $1.name.count) || ($0.name < $1.name) {\n return true\n }\n return false\n })\n try Self.write(buffer: &buffer, attrs: attributes, start: UInt16(idx), delta: UInt16(idx), inline: false)\n }\n\n /// Writes the specified list of extended attribute entries and their values to the provided\n /// This method does not fill in any headers (Inode inline / block level) that may be required to parse these attributes\n ///\n /// - Parameters:\n /// - buffer: An array of [UInt8] where the data will be written into\n /// - attrs: The list of ExtendedAttributes to write\n /// - start: the index from where data should be put into the buffer - useful when if you dont want this method to be overwriting existing data\n /// - delta: index from where the begin the offset calculations\n /// - inline: if the byte buffer being written into is an inline data block for an inode: Determines the hash calculation\n private static func write(\n buffer: inout [UInt8], attrs: [ExtendedAttribute], start: UInt16, delta: UInt16, inline: Bool\n ) throws {\n var offset: UInt16 = UInt16(buffer.count) + delta - start\n var front = Int(start)\n var end = buffer.count\n\n for attribute in attrs {\n guard end - front >= 4 else {\n throw Error.malformedXattrBuffer\n }\n\n var out: [UInt8] = []\n let v = attribute.sizeValue\n offset -= UInt16(v)\n out.append(UInt8(attribute.name.count))\n out.append(attribute.index)\n withUnsafeLittleEndianBytes(\n of: UInt16(offset),\n body: { bytes in\n out.append(contentsOf: bytes)\n })\n out.append(contentsOf: [0, 0, 0, 0]) // these next four bytes indicate that the attr values are in the same block\n withUnsafeLittleEndianBytes(\n of: UInt32(attribute.value.count),\n body: { bytes in\n out.append(contentsOf: bytes)\n })\n if !inline {\n withUnsafeLittleEndianBytes(\n of: UInt32(attribute.hash),\n body: { bytes in\n out.append(contentsOf: bytes)\n })\n } else {\n out.append(contentsOf: [0, 0, 0, 0])\n }\n guard let name = attribute.name.data(using: .ascii) else {\n throw Error.convertAsciiString(attribute.name)\n }\n out.append(contentsOf: [UInt8](name))\n while out.count < Int(attribute.sizeEntry) { // ensure that xattr entry size is a multiple of 4\n out.append(0)\n }\n for (i, byte) in out.enumerated() {\n buffer[front + i] = byte\n }\n front += out.count\n\n end -= Int(attribute.sizeValue)\n for (i, byte) in attribute.value.enumerated() {\n buffer[end + i] = byte\n }\n }\n }\n\n public static func read(buffer: [UInt8], start: Int, offset: Int) throws -> [ExtendedAttribute] {\n var i = start\n var attribs: [ExtendedAttribute] = []\n // 16 is the size of 1 XAttrEntry\n while i + 16 < buffer.count {\n let attributeStart = i\n let rawXattrEntry = Array(buffer[i.. URL {\n let dir = FileManager.default.uniqueTemporaryDirectory(create: true)\n try \"hello\".write(to: dir.appendingPathComponent(\"hi.txt\"), atomically: true, encoding: .utf8)\n return dir\n }\n}\n"], ["/containerization/Sources/Integration/ProcessTests.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Crypto\nimport Foundation\nimport Logging\n\nextension IntegrationSuite {\n func testProcessTrue() async throws {\n let id = \"test-process-true\"\n\n let bs = try await bootstrap()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/true\"]\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n }\n\n func testProcessFalse() async throws {\n let id = \"test-process-false\"\n\n let bs = try await bootstrap()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/false\"]\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 1 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 1\")\n }\n }\n\n final class BufferWriter: Writer {\n nonisolated(unsafe) var data = Data()\n\n func write(_ data: Data) throws {\n guard data.count > 0 else {\n return\n }\n self.data.append(data)\n }\n }\n\n final class StdinBuffer: ReaderStream {\n let data: Data\n\n init(data: Data) {\n self.data = data\n }\n\n func stream() -> AsyncStream {\n let (stream, cont) = AsyncStream.makeStream()\n cont.yield(self.data)\n cont.finish()\n return stream\n }\n }\n\n func testProcessEchoHi() async throws {\n let id = \"test-process-echo-hi\"\n let bs = try await bootstrap()\n\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/echo\", \"hi\"]\n config.process.stdout = buffer\n }\n\n do {\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 1\")\n }\n\n guard String(data: buffer.data, encoding: .utf8) == \"hi\\n\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned on stdout 'hi' != '\\(String(data: buffer.data, encoding: .utf8)!)'\")\n }\n } catch {\n try? await container.stop()\n throw error\n }\n }\n\n func testMultipleConcurrentProcesses() async throws {\n let id = \"test-concurrent-processes\"\n\n let bs = try await bootstrap()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/sleep\", \"1000\"]\n }\n\n do {\n try await container.create()\n try await container.start()\n\n try await withThrowingTaskGroup(of: Void.self) { group in\n for i in 0...80 {\n let exec = try await container.exec(\"exec-\\(i)\") { config in\n config.arguments = [\"/bin/true\"]\n }\n\n group.addTask {\n try await exec.start()\n let status = try await exec.wait()\n if status != 0 {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n try await exec.delete()\n }\n }\n\n // wait for all the exec'd processes.\n try await group.waitForAll()\n print(\"all group processes exit\")\n\n // kill the init process.\n try await container.kill(SIGKILL)\n let status = try await container.wait()\n try await container.stop()\n print(\"\\(status)\")\n }\n } catch {\n throw error\n }\n }\n\n func testMultipleConcurrentProcessesOutputStress() async throws {\n let id = \"test-concurrent-processes-output-stress\"\n let bs = try await bootstrap()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/sleep\", \"1000\"]\n }\n\n do {\n try await container.create()\n try await container.start()\n\n let buffer = BufferWriter()\n let exec = try await container.exec(\"expected-value\") { config in\n config.arguments = [\n \"sh\",\n \"-c\",\n \"dd if=/dev/random of=/tmp/bytes bs=1M count=20 status=none ; sha256sum /tmp/bytes\",\n ]\n config.stdout = buffer\n }\n\n try await exec.start()\n let status = try await exec.wait()\n if status != 0 {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n let output = String(data: buffer.data, encoding: .utf8)!\n let expected = String(output.split(separator: \" \").first!)\n try await withThrowingTaskGroup(of: Void.self) { group in\n for i in 0...80 {\n let idx = i\n group.addTask {\n let buffer = BufferWriter()\n let exec = try await container.exec(\"exec-\\(idx)\") { config in\n config.arguments = [\"cat\", \"/tmp/bytes\"]\n config.stdout = buffer\n }\n try await exec.start()\n\n let status = try await exec.wait()\n if status != 0 {\n throw IntegrationError.assert(msg: \"process \\(idx) status \\(status) != 0\")\n }\n\n var hasher = SHA256()\n hasher.update(data: buffer.data)\n let hash = hasher.finalize().digestString.trimmingDigestPrefix\n guard hash == expected else {\n throw IntegrationError.assert(\n msg: \"process \\(idx) output \\(hash) != expected \\(expected)\")\n }\n try await exec.delete()\n }\n }\n\n // wait for all the exec'd processes.\n try await group.waitForAll()\n print(\"all group processes exit\")\n\n // kill the init process.\n try await container.kill(SIGKILL)\n try await container.wait()\n try await container.stop()\n }\n }\n }\n\n func testProcessUser() async throws {\n let id = \"test-process-user\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/usr/bin/id\"]\n config.process.user = .init(uid: 1, gid: 1, additionalGids: [1])\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n let expected = \"uid=1(bin) gid=1(bin) groups=1(bin)\"\n\n guard String(data: buffer.data, encoding: .utf8) == \"\\(expected)\\n\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned on stdout '\\(expected)' != '\\(String(data: buffer.data, encoding: .utf8)!)'\")\n }\n }\n\n // Ensure if we ask for a terminal we set TERM.\n func testProcessTtyEnvvar() async throws {\n let id = \"test-process-tty-envvar\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"env\"]\n config.process.terminal = true\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n guard let str = String(data: buffer.data, encoding: .utf8) else {\n throw IntegrationError.assert(\n msg: \"failed to convert standard output to a UTF8 string\")\n }\n\n let homeEnvvar = \"TERM=xterm\"\n guard str.contains(homeEnvvar) else {\n throw IntegrationError.assert(\n msg: \"process should have TERM environment variable defined\")\n }\n }\n\n // Make sure we set HOME by default if we can find it in /etc/passwd in the guest.\n func testProcessHomeEnvvar() async throws {\n let id = \"test-process-home-envvar\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"env\"]\n config.process.user = .init(uid: 0, gid: 0)\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n guard let str = String(data: buffer.data, encoding: .utf8) else {\n throw IntegrationError.assert(\n msg: \"failed to convert standard output to a UTF8 string\")\n }\n\n let homeEnvvar = \"HOME=/root\"\n guard str.contains(homeEnvvar) else {\n throw IntegrationError.assert(\n msg: \"process should have HOME environment variable defined\")\n }\n }\n\n func testProcessCustomHomeEnvvar() async throws {\n let id = \"test-process-custom-home-envvar\"\n\n let bs = try await bootstrap()\n let customHomeEnvvar = \"HOME=/tmp/custom/home\"\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"sh\", \"-c\", \"echo HOME=$HOME\"]\n config.process.environmentVariables.append(customHomeEnvvar)\n config.process.user = .init(uid: 0, gid: 0)\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n guard let output = String(data: buffer.data, encoding: .utf8) else {\n throw IntegrationError.assert(msg: \"failed to convert stdout to UTF8\")\n }\n\n guard output.contains(customHomeEnvvar) else {\n throw IntegrationError.assert(msg: \"process should have preserved custom HOME environment variable, expected \\(customHomeEnvvar), got: \\(output)\")\n }\n }\n\n func testHostname() async throws {\n let id = \"test-container-hostname\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"/bin/hostname\"]\n config.hostname = \"foo-bar\"\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n let expected = \"foo-bar\"\n\n guard String(data: buffer.data, encoding: .utf8) == \"\\(expected)\\n\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned on stdout '\\(expected)' != '\\(String(data: buffer.data, encoding: .utf8)!)'\")\n }\n }\n\n func testHostsFile() async throws {\n let id = \"test-container-hosts-file\"\n\n let bs = try await bootstrap()\n let entry = Hosts.Entry.localHostIPV4(comment: \"Testaroo\")\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"cat\", \"/etc/hosts\"]\n config.hosts = Hosts(entries: [entry])\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n\n let expected = entry.rendered\n guard String(data: buffer.data, encoding: .utf8) == \"\\(expected)\\n\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned on stdout '\\(expected)' != '\\(String(data: buffer.data, encoding: .utf8)!)'\")\n }\n }\n\n func testProcessStdin() async throws {\n let id = \"test-container-stdin\"\n\n let bs = try await bootstrap()\n let buffer = BufferWriter()\n let container = try LinuxContainer(id, rootfs: bs.rootfs, vmm: bs.vmm) { config in\n config.process.arguments = [\"cat\"]\n config.process.stdin = StdinBuffer(data: \"Hello from test\".data(using: .utf8)!)\n config.process.stdout = buffer\n }\n\n try await container.create()\n try await container.start()\n\n let status = try await container.wait()\n try await container.stop()\n\n guard status == 0 else {\n throw IntegrationError.assert(msg: \"process status \\(status) != 0\")\n }\n let expected = \"Hello from test\"\n\n guard String(data: buffer.data, encoding: .utf8) == \"\\(expected)\" else {\n throw IntegrationError.assert(\n msg: \"process should have returned on stdout '\\(expected)' != '\\(String(data: buffer.data, encoding: .utf8)!)'\")\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Signals.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Helper type with utilities to parse and manipulate unix signals.\npublic struct Signals {\n /// Returns the numeric values of all known signals.\n public static func allNumeric() -> [Int32] {\n Array(Signals.all.values)\n }\n\n /// Parses a string representation of a signal (SIGKILL) and returns\n // the 32 bit integer representation (9).\n public static func parseSignal(_ signal: String) throws -> Int32 {\n if let sig = Int32(signal) {\n if !Signals.all.values.contains(sig) {\n throw Error.invalidSignal(signal)\n }\n return sig\n }\n var signalUpper = signal.uppercased()\n signalUpper.trimPrefix(\"SIG\")\n guard let sig = Signals.all[signalUpper] else {\n throw Error.invalidSignal(signal)\n }\n return sig\n }\n\n /// Errors that can be encountered for converting signals.\n public enum Error: Swift.Error, CustomStringConvertible {\n case invalidSignal(String)\n\n public var description: String {\n switch self {\n case .invalidSignal(let sig):\n return \"invalid signal: \\(sig)\"\n }\n }\n }\n}\n\n#if os(macOS)\n\nextension Signals {\n /// `all` returns all signals for the current platform.\n public static let all: [String: Int32] = [\n \"ABRT\": SIGABRT,\n \"ALRM\": SIGALRM,\n \"BUS\": SIGBUS,\n \"CHLD\": SIGCHLD,\n \"CONT\": SIGCONT,\n \"EMT\": SIGEMT,\n \"FPE\": SIGFPE,\n \"HUP\": SIGHUP,\n \"ILL\": SIGILL,\n \"INFO\": SIGINFO,\n \"INT\": SIGINT,\n \"IO\": SIGIO,\n \"IOT\": SIGIOT,\n \"KILL\": SIGKILL,\n \"PIPE\": SIGPIPE,\n \"PROF\": SIGPROF,\n \"QUIT\": SIGQUIT,\n \"SEGV\": SIGSEGV,\n \"STOP\": SIGSTOP,\n \"SYS\": SIGSYS,\n \"TERM\": SIGTERM,\n \"TRAP\": SIGTRAP,\n \"TSTP\": SIGTSTP,\n \"TTIN\": SIGTTIN,\n \"TTOU\": SIGTTOU,\n \"URG\": SIGURG,\n \"USR1\": SIGUSR1,\n \"USR2\": SIGUSR2,\n \"VTALRM\": SIGVTALRM,\n \"WINCH\": SIGWINCH,\n \"XCPU\": SIGXCPU,\n \"XFSZ\": SIGXFSZ,\n ]\n}\n\n#endif\n\n#if os(Linux)\n\nextension Signals {\n /// `all` returns all signals for the current platform.\n ///\n /// For Linux this isn't actually exhaustive as it excludes\n /// rtmin/rtmax entries.\n public static let all: [String: Int32] = [\n \"ABRT\": SIGABRT,\n \"ALRM\": SIGALRM,\n \"BUS\": SIGBUS,\n \"CHLD\": SIGCHLD,\n \"CLD\": SIGCHLD,\n \"CONT\": SIGCONT,\n \"FPE\": SIGFPE,\n \"HUP\": SIGHUP,\n \"ILL\": SIGILL,\n \"INT\": SIGINT,\n \"IO\": SIGIO,\n \"IOT\": SIGIOT,\n \"KILL\": SIGKILL,\n \"PIPE\": SIGPIPE,\n \"POLL\": SIGPOLL,\n \"PROF\": SIGPROF,\n \"PWR\": SIGPWR,\n \"QUIT\": SIGQUIT,\n \"SEGV\": SIGSEGV,\n \"STKFLT\": SIGSTKFLT,\n \"STOP\": SIGSTOP,\n \"SYS\": SIGSYS,\n \"TERM\": SIGTERM,\n \"TRAP\": SIGTRAP,\n \"TSTP\": SIGTSTP,\n \"TTIN\": SIGTTIN,\n \"TTOU\": SIGTTOU,\n \"URG\": SIGURG,\n \"USR1\": SIGUSR1,\n \"USR2\": SIGUSR2,\n \"VTALRM\": SIGVTALRM,\n \"WINCH\": SIGWINCH,\n \"XCPU\": SIGXCPU,\n \"XFSZ\": SIGXFSZ,\n ]\n}\n\n#endif\n"], ["/containerization/Sources/ContainerizationOS/User.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\n\n/// `User` provides utilities to ensure that a given username exists in\n/// /etc/passwd (and /etc/group).\npublic enum User {\n private static let passwdFile = \"/etc/passwd\"\n private static let groupFile = \"/etc/group\"\n\n public struct ExecUser: Sendable {\n public var uid: UInt32\n public var gid: UInt32\n public var sgids: [UInt32]\n public var home: String\n }\n\n private struct User {\n let name: String\n let password: String\n let uid: UInt32\n let gid: UInt32\n let gecos: String\n let home: String\n let shell: String\n\n /// The argument `rawString` must follow the below format.\n /// Name:Password:Uid:Gid:Gecos:Home:Shell\n init(rawString: String) throws {\n let args = rawString.split(separator: \":\", omittingEmptySubsequences: false)\n guard args.count == 7 else {\n throw ContainerizationError.init(.invalidArgument, message: \"Cannot parse User from '\\(rawString)'\")\n }\n guard let uid = UInt32(args[2]) else {\n throw ContainerizationError.init(.invalidArgument, message: \"Cannot parse uid from '\\(args[2])'\")\n }\n guard let gid = UInt32(args[3]) else {\n throw ContainerizationError.init(.invalidArgument, message: \"Cannot parse gid from '\\(args[3])'\")\n }\n self.name = String(args[0])\n self.password = String(args[1])\n self.uid = uid\n self.gid = gid\n self.gecos = String(args[4])\n self.home = String(args[5])\n self.shell = String(args[6])\n }\n }\n\n private struct Group {\n let name: String\n let password: String\n let gid: UInt32\n let users: [String]\n\n /// The argument `rawString` must follow the below format.\n /// Name:Password:Gid:user1,user2\n init(rawString: String) throws {\n let args = rawString.split(separator: \":\", omittingEmptySubsequences: false)\n guard args.count == 4 else {\n throw ContainerizationError.init(.invalidArgument, message: \"Cannot parse Group from '\\(rawString)'\")\n }\n guard let gid = UInt32(args[2]) else {\n throw ContainerizationError.init(.invalidArgument, message: \"Cannot parse gid from '\\(args[2])'\")\n }\n self.name = String(args[0])\n self.password = String(args[1])\n self.gid = gid\n self.users = args[3].split(separator: \",\").map { String($0) }\n }\n }\n}\n\n// MARK: Private methods\n\nextension User {\n /// Parse the contents of the passwd file\n private static func parsePasswd(passwdFile: URL) throws -> [User] {\n var users: [User] = []\n try self.parse(file: passwdFile) { line in\n let user = try User(rawString: line)\n users.append(user)\n }\n return users\n }\n\n /// Parse the contents of the group file\n private static func parseGroup(groupFile: URL) throws -> [Group] {\n var groups: [Group] = []\n try self.parse(file: groupFile) { line in\n let group = try Group(rawString: line)\n groups.append(group)\n }\n return groups\n }\n\n private static func parse(file: URL, handler: (_ line: String) throws -> Void) throws {\n let fm = FileManager.default\n guard fm.fileExists(atPath: file.absolutePath()) else {\n throw ContainerizationError(.notFound, message: \"File \\(file.absolutePath()) does not exist\")\n }\n let content = try String(contentsOf: file, encoding: .ascii)\n let lines = content.components(separatedBy: .newlines)\n for line in lines {\n guard !line.isEmpty else {\n continue\n }\n try handler(line.trimmingCharacters(in: .whitespaces))\n }\n }\n}\n\n// MARK: Public methods\n\nextension User {\n public static func parseUser(root: String, userString: String) throws -> ExecUser {\n let defaultUser = ExecUser(uid: 0, gid: 0, sgids: [], home: \"/\")\n guard !userString.isEmpty else {\n return defaultUser\n }\n\n let passwdPath = URL(filePath: root).appending(path: Self.passwdFile)\n let groupPath = URL(filePath: root).appending(path: Self.groupFile)\n let parts = userString.split(separator: \":\", maxSplits: 1, omittingEmptySubsequences: false)\n\n let userArg = String(parts[0])\n let userIdArg = Int(userArg)\n\n guard FileManager.default.fileExists(atPath: passwdPath.absolutePath()) else {\n guard let userIdArg else {\n throw ContainerizationError(.internalError, message: \"Cannot parse username \\(userArg)\")\n }\n let uid = UInt32(userIdArg)\n guard parts.count > 1 else {\n return ExecUser(uid: uid, gid: uid, sgids: [], home: \"/\")\n }\n guard let gid = UInt32(String(parts[1])) else {\n throw ContainerizationError(.internalError, message: \"Cannot parse user group from \\(userString)\")\n }\n return ExecUser(uid: uid, gid: gid, sgids: [], home: \"/\")\n }\n\n let registeredUsers = try parsePasswd(passwdFile: passwdPath)\n guard registeredUsers.count > 0 else {\n throw ContainerizationError(.internalError, message: \"No users configured in passwd file.\")\n }\n let matches = registeredUsers.filter { registeredUser in\n // Check for a match (either uid/name) against the configured users from the passwd file.\n // We have to check both the uid and the name cause we dont know the type of `userString`\n registeredUser.name == userArg || registeredUser.uid == (userIdArg ?? -1)\n }\n guard let match = matches.first else {\n // We did not find a matching uid/username in the passwd file\n throw ContainerizationError(.internalError, message: \"Cannot find User '\\(userArg)' in passwd file.\")\n }\n\n var user = ExecUser(uid: match.uid, gid: match.gid, sgids: [match.gid], home: match.home)\n\n guard !match.name.isEmpty else {\n return user\n }\n let matchedUser = match.name\n var groupArg = \"\"\n var groupIdArg: Int? = nil\n if parts.count > 1 {\n groupArg = String(parts[1])\n groupIdArg = Int(groupArg)\n }\n\n let registeredGroups: [Group] = {\n do {\n // Parse the /etc/group file for a list of registered groups.\n // If the file is missing / malformed, we bail out\n return try parseGroup(groupFile: groupPath)\n } catch {\n return []\n }\n }()\n guard registeredGroups.count > 0 else {\n return user\n }\n let matchingGroups = registeredGroups.filter { registeredGroup in\n if !groupArg.isEmpty {\n return registeredGroup.gid == (groupIdArg ?? -1) || registeredGroup.name == groupArg\n }\n return registeredGroup.users.contains(matchedUser) || registeredGroup.gid == match.gid\n }\n guard matchingGroups.count > 0 else {\n throw ContainerizationError(.internalError, message: \"Cannot find Group '\\(groupArg)' in groups file.\")\n }\n // We have found a list of groups that match the group specified in the argument `userString`.\n // Set the matched groups as the supplement groups for the user\n if !groupArg.isEmpty {\n // Reassign the user's group only we were explicitly asked for a group\n user.gid = matchingGroups.first!.gid\n user.sgids = matchingGroups.map { group in\n group.gid\n }\n } else {\n user.sgids.append(\n contentsOf: matchingGroups.map { group in\n group.gid\n })\n }\n return user\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/State.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic enum ContainerState: String, Codable, Sendable {\n case creating\n case created\n case running\n case stopped\n}\n\npublic struct State: Codable, Sendable {\n public init(\n version: String,\n id: String,\n status: ContainerState,\n pid: Int,\n bundle: String,\n annotations: [String: String]?\n ) {\n self.ociVersion = version\n self.id = id\n self.status = status\n self.pid = pid\n self.bundle = bundle\n self.annotations = annotations\n }\n\n public init(instance: State) {\n self.ociVersion = instance.ociVersion\n self.id = instance.id\n self.status = instance.status\n self.pid = instance.pid\n self.bundle = instance.bundle\n self.annotations = instance.annotations\n }\n\n public let ociVersion: String\n public let id: String\n public let status: ContainerState\n public let pid: Int\n public let bundle: String\n public var annotations: [String: String]?\n}\n\npublic let seccompFdName: String = \"seccompFd\"\n\npublic struct ContainerProcessState: Codable, Sendable {\n public init(version: String, fds: [String], pid: Int, metadata: String, state: State) {\n self.ociVersion = version\n self.fds = fds\n self.pid = pid\n self.metadata = metadata\n self.state = state\n }\n\n public init(instance: ContainerProcessState) {\n self.ociVersion = instance.ociVersion\n self.fds = instance.fds\n self.pid = instance.pid\n self.metadata = instance.metadata\n self.state = instance.state\n }\n\n public let ociVersion: String\n public var fds: [String]\n public let pid: Int\n public let metadata: String\n public let state: State\n}\n"], ["/containerization/Sources/ContainerizationError/ContainerizationError.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// The core error type for Containerization.\n///\n/// Most API surfaces for the core container/process/agent types will\n/// return a ContainerizationError.\npublic struct ContainerizationError: Swift.Error, Sendable {\n /// A code describing the error encountered.\n public var code: Code\n /// A description of the error.\n public var message: String\n /// The original error which led to this error being thrown.\n public var cause: (any Error)?\n\n /// Creates a new error.\n ///\n /// - Parameters:\n /// - code: The error code.\n /// - message: A description of the error.\n /// - cause: The original error which led to this error being thrown.\n public init(_ code: Code, message: String, cause: (any Error)? = nil) {\n self.code = code\n self.message = message\n self.cause = cause\n }\n\n /// Creates a new error.\n ///\n /// - Parameters:\n /// - rawCode: The error code value as a String.\n /// - message: A description of the error.\n /// - cause: The original error which led to this error being thrown.\n public init(_ rawCode: String, message: String, cause: (any Error)? = nil) {\n self.code = Code(rawValue: rawCode)\n self.message = message\n self.cause = cause\n }\n\n /// Provides a unique hash of the error.\n public func hash(into hasher: inout Hasher) {\n hasher.combine(self.code)\n hasher.combine(self.message)\n }\n\n /// Equality operator for the error. Uses the code and message.\n public static func == (lhs: Self, rhs: Self) -> Bool {\n lhs.code == rhs.code && lhs.message == rhs.message\n }\n\n /// Checks if the given error has the provided code.\n public func isCode(_ code: Code) -> Bool {\n self.code == code\n }\n}\n\nextension ContainerizationError: CustomStringConvertible {\n /// Description of the error.\n public var description: String {\n guard let cause = self.cause else {\n return \"\\(self.code): \\\"\\(self.message)\\\"\"\n }\n return \"\\(self.code): \\\"\\(self.message)\\\" (cause: \\\"\\(cause)\\\")\"\n }\n}\n\nextension ContainerizationError {\n /// Codes for a `ContainerizationError`.\n public struct Code: Sendable, Hashable {\n private enum Value: Hashable, Sendable, CaseIterable {\n case unknown\n case invalidArgument\n case internalError\n case exists\n case notFound\n case cancelled\n case invalidState\n case empty\n case timeout\n case unsupported\n case interrupted\n }\n\n private var value: Value\n private init(_ value: Value) {\n self.value = value\n }\n\n init(rawValue: String) {\n let values = Value.allCases.reduce(into: [String: Value]()) {\n $0[String(describing: $1)] = $1\n }\n\n let match = values[rawValue]\n guard let match else {\n fatalError(\"invalid Code Value \\(rawValue)\")\n }\n self.value = match\n }\n\n public static var unknown: Self {\n Self(.unknown)\n }\n\n public static var invalidArgument: Self {\n Self(.invalidArgument)\n }\n\n public static var internalError: Self {\n Self(.internalError)\n }\n\n public static var exists: Self {\n Self(.exists)\n }\n\n public static var notFound: Self {\n Self(.notFound)\n }\n\n public static var cancelled: Self {\n Self(.cancelled)\n }\n\n public static var invalidState: Self {\n Self(.invalidState)\n }\n\n public static var empty: Self {\n Self(.empty)\n }\n\n public static var timeout: Self {\n Self(.timeout)\n }\n\n public static var unsupported: Self {\n Self(.unsupported)\n }\n\n public static var interrupted: Self {\n Self(.interrupted)\n }\n }\n}\n\nextension ContainerizationError.Code: CustomStringConvertible {\n public var description: String {\n String(describing: self.value)\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/RegistryClient+Push.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport ContainerizationError\nimport ContainerizationExtras\nimport Foundation\nimport NIO\n\nextension RegistryClient {\n /// Pushes the content specified by a descriptor to a remote registry.\n /// - Parameters:\n /// - name: The namespace which the descriptor should belong under.\n /// - tag: The tag or digest for uniquely identifying the manifest.\n /// By convention, any portion that may be a partial or whole digest\n /// will be proceeded by an `@`. Anything preceding the `@` will be referred\n /// to as \"tag\".\n /// This is usually broken down into the following possibilities:\n /// 1. \n /// 2. @\n /// 3. @\n /// The tag is anything except `@` and `:`, and digest is anything after the `@`\n /// - descriptor: The OCI descriptor of the content to be pushed.\n /// - streamGenerator: A closure that produces an`AsyncStream` of `ByteBuffer`\n /// for streaming data to the `HTTPClientRequest.Body`.\n /// The caller is responsible for providing the `AsyncStream` where the data may come from\n /// a file on disk, data in memory, etc.\n /// - progress: The progress handler to invoke as data is sent.\n public func push(\n name: String,\n ref tag: String,\n descriptor: Descriptor,\n streamGenerator: () throws -> T,\n progress: ProgressHandler?\n ) async throws where T.Element == ByteBuffer {\n var components = base\n\n let mediaType = descriptor.mediaType\n if mediaType.isEmpty {\n throw ContainerizationError(.invalidArgument, message: \"Missing media type for descriptor \\(descriptor.digest)\")\n }\n\n var isManifest = false\n var existCheck: [String] = []\n\n switch mediaType {\n case MediaTypes.dockerManifest, MediaTypes.dockerManifestList, MediaTypes.imageManifest, MediaTypes.index:\n isManifest = true\n existCheck = self.getManifestPath(tag: tag, digest: descriptor.digest)\n default:\n existCheck = [\"blobs\", descriptor.digest]\n }\n\n // Check if the content already exists.\n components.path = \"/v2/\\(name)/\\(existCheck.joined(separator: \"/\"))\"\n\n let mediaTypes = [\n mediaType,\n \"*/*\",\n ]\n\n var headers = [\n (\"Accept\", mediaTypes.joined(separator: \", \"))\n ]\n\n try await request(components: components, method: .HEAD, headers: headers) { response in\n if response.status == .ok {\n var exists = false\n if isManifest && existCheck[1] != descriptor.digest {\n if descriptor.digest == response.headers.first(name: \"Docker-Content-Digest\") {\n exists = true\n }\n } else {\n exists = true\n }\n\n if exists {\n throw ContainerizationError(.exists, message: \"Content already exists \\(descriptor.digest)\")\n }\n } else if response.status != .notFound {\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n }\n\n if isManifest {\n let path = self.getManifestPath(tag: tag, digest: descriptor.digest)\n components.path = \"/v2/\\(name)/\\(path.joined(separator: \"/\"))\"\n headers = [\n (\"Content-Type\", mediaType)\n ]\n } else {\n // Start upload request for blobs.\n components.path = \"/v2/\\(name)/blobs/uploads/\"\n try await request(components: components, method: .POST) { response in\n switch response.status {\n case .ok, .accepted, .noContent:\n break\n case .created:\n throw ContainerizationError(.exists, message: \"Content already exists \\(descriptor.digest)\")\n default:\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n\n // Get the location to upload the blob.\n guard let location = response.headers.first(name: \"Location\") else {\n throw ContainerizationError(.invalidArgument, message: \"Missing required header Location\")\n }\n\n guard let urlComponents = URLComponents(string: location) else {\n throw ContainerizationError(.invalidArgument, message: \"Invalid url \\(location)\")\n }\n var queryItems = urlComponents.queryItems ?? []\n queryItems.append(URLQueryItem(name: \"digest\", value: descriptor.digest))\n components.path = urlComponents.path\n components.queryItems = queryItems\n headers = [\n (\"Content-Type\", \"application/octet-stream\"),\n (\"Content-Length\", String(descriptor.size)),\n ]\n }\n }\n\n // We have to pass a body closure rather than a body to reset the stream when retrying.\n let bodyClosure = {\n let stream = try streamGenerator()\n let body = HTTPClientRequest.Body.stream(stream, length: .known(descriptor.size))\n return body\n }\n\n return try await request(components: components, method: .PUT, bodyClosure: bodyClosure, headers: headers) { response in\n switch response.status {\n case .ok, .created, .noContent:\n break\n default:\n let url = components.url?.absoluteString ?? \"unknown\"\n let reason = await ErrorResponse.fromResponseBody(response.body)?.jsonString\n throw Error.invalidStatus(url: url, response.status, reason: reason)\n }\n\n guard descriptor.digest == response.headers.first(name: \"Docker-Content-Digest\") else {\n let required = response.headers.first(name: \"Docker-Content-Digest\") ?? \"\"\n throw ContainerizationError(.internalError, message: \"Digest mismatch \\(descriptor.digest) != \\(required)\")\n }\n }\n }\n\n private func getManifestPath(tag: String, digest: String) -> [String] {\n var object = tag\n if let i = tag.firstIndex(of: \"@\") {\n let index = tag.index(after: i)\n if String(tag[index...]) != digest {\n object = \"\"\n } else {\n object = String(tag[...i])\n }\n }\n\n if object == \"\" {\n return [\"manifests\", digest]\n }\n\n return [\"manifests\", object]\n }\n}\n"], ["/containerization/vminitd/Sources/vmexec/ExecCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport ContainerizationOCI\nimport Foundation\nimport LCShim\nimport Logging\nimport Musl\n\nstruct ExecCommand: ParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"exec\",\n abstract: \"Exec in a container\"\n )\n\n @Option(name: .long, help: \"path to an OCI runtime spec process configuration\")\n var processPath: String\n\n @Option(name: .long, help: \"pid of the init process for the container\")\n var parentPid: Int\n\n func run() throws {\n LoggingSystem.bootstrap(App.standardError)\n let log = Logger(label: \"vmexec\")\n\n let src = URL(fileURLWithPath: processPath)\n let processBytes = try Data(contentsOf: src)\n let process = try JSONDecoder().decode(\n ContainerizationOCI.Process.self,\n from: processBytes\n )\n try execInNamespaces(process: process, log: log)\n }\n\n static func enterNS(path: String, nsType: Int32) throws {\n let fd = open(path, O_RDONLY)\n if fd <= 0 {\n throw App.Errno(stage: \"open(ns)\")\n }\n defer { close(fd) }\n\n guard setns(fd, nsType) == 0 else {\n throw App.Errno(stage: \"setns(fd)\")\n }\n }\n\n private func execInNamespaces(\n process: ContainerizationOCI.Process,\n log: Logger\n ) throws {\n // CLOEXEC the pipe fd that signals process readiness.\n let syncfd = FileHandle(fileDescriptor: 3)\n if fcntl(3, F_SETFD, FD_CLOEXEC) == -1 {\n throw App.Errno(stage: \"cloexec(syncfd)\")\n }\n\n try Self.enterNS(path: \"/proc/\\(self.parentPid)/ns/cgroup\", nsType: CLONE_NEWCGROUP)\n try Self.enterNS(path: \"/proc/\\(self.parentPid)/ns/pid\", nsType: CLONE_NEWPID)\n try Self.enterNS(path: \"/proc/\\(self.parentPid)/ns/uts\", nsType: CLONE_NEWUTS)\n try Self.enterNS(path: \"/proc/\\(self.parentPid)/ns/mnt\", nsType: CLONE_NEWNS)\n\n let childPipe = Pipe()\n try childPipe.setCloexec()\n let processID = fork()\n\n guard processID != -1 else {\n try? childPipe.fileHandleForReading.close()\n try? childPipe.fileHandleForWriting.close()\n try? syncfd.close()\n\n throw App.Errno(stage: \"fork\")\n }\n\n if processID == 0 { // child\n try childPipe.fileHandleForReading.close()\n try syncfd.close()\n\n guard setsid() != -1 else {\n throw App.Errno(stage: \"setsid()\")\n }\n\n // Apply O_CLOEXEC to all file descriptors except stdio.\n // This ensures that all unwanted fds we may have accidentally\n // inherited are marked close-on-exec so they stay out of the\n // container.\n try App.applyCloseExecOnFDs()\n try App.setRLimits(rlimits: process.rlimits)\n\n // Change stdio to be owned by the requested user.\n try App.fixStdioPerms(user: process.user)\n\n // Set uid, gid, and supplementary groups\n try App.setPermissions(user: process.user)\n\n if process.terminal {\n guard ioctl(0, UInt(TIOCSCTTY), 0) != -1 else {\n throw App.Errno(stage: \"setctty()\")\n }\n }\n\n try App.exec(process: process)\n } else { // parent process\n try childPipe.fileHandleForWriting.close()\n\n // wait until the pipe is closed then carry on.\n _ = try childPipe.fileHandleForReading.readToEnd()\n try childPipe.fileHandleForReading.close()\n\n // send our child's pid to our parent before we exit.\n var childPid = processID\n let data = Data(bytes: &childPid, count: MemoryLayout.size(ofValue: childPid))\n\n try syncfd.write(contentsOf: data)\n try syncfd.close()\n }\n }\n}\n"], ["/containerization/Sources/Containerization/Agent/Vminitd+SocketRelay.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension Vminitd: SocketRelayAgent {\n /// Sets up a relay between a host socket to a newly created guest socket, or vice versa.\n public func relaySocket(port: UInt32, configuration: UnixSocketConfiguration) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_ProxyVsockRequest.with {\n $0.id = configuration.id\n $0.vsockPort = port\n\n if let perms = configuration.permissions {\n $0.guestSocketPermissions = UInt32(perms.rawValue)\n }\n\n switch configuration.direction {\n case .into:\n $0.guestPath = configuration.destination.path\n $0.action = .into\n case .outOf:\n $0.guestPath = configuration.source.path\n $0.action = .outOf\n }\n }\n _ = try await client.proxyVsock(request)\n }\n\n /// Stops the specified socket relay.\n public func stopSocketRelay(configuration: UnixSocketConfiguration) async throws {\n let request = Com_Apple_Containerization_Sandbox_V3_StopVsockProxyRequest.with {\n $0.id = configuration.id\n }\n _ = try await client.stopVsockProxy(request)\n }\n}\n"], ["/containerization/Sources/ContainerizationNetlink/Types.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport Foundation\n\nstruct SocketType {\n static let SOCK_RAW: Int32 = 3\n}\n\nstruct AddressFamily {\n static let AF_UNSPEC: UInt16 = 0\n static let AF_INET: UInt16 = 2\n static let AF_INET6: UInt16 = 10\n static let AF_NETLINK: UInt16 = 16\n static let AF_PACKET: UInt16 = 17\n}\n\nstruct NetlinkProtocol {\n static let NETLINK_ROUTE: Int32 = 0\n}\n\nstruct NetlinkType {\n static let NLMSG_NOOP: UInt16 = 1\n static let NLMSG_ERROR: UInt16 = 2\n static let NLMSG_DONE: UInt16 = 3\n static let NLMSG_OVERRUN: UInt16 = 4\n static let RTM_NEWLINK: UInt16 = 16\n static let RTM_DELLINK: UInt16 = 17\n static let RTM_GETLINK: UInt16 = 18\n static let RTM_NEWADDR: UInt16 = 20\n static let RTM_NEWROUTE: UInt16 = 24\n}\n\nstruct NetlinkFlags {\n static let NLM_F_REQUEST: UInt16 = 0x01\n static let NLM_F_MULTI: UInt16 = 0x02\n static let NLM_F_ACK: UInt16 = 0x04\n static let NLM_F_ECHO: UInt16 = 0x08\n static let NLM_F_DUMP_INTR: UInt16 = 0x10\n static let NLM_F_DUMP_FILTERED: UInt16 = 0x20\n\n // GET request\n static let NLM_F_ROOT: UInt16 = 0x100\n static let NLM_F_MATCH: UInt16 = 0x200\n static let NLM_F_ATOMIC: UInt16 = 0x400\n static let NLM_F_DUMP: UInt16 = NetlinkFlags.NLM_F_ROOT | NetlinkFlags.NLM_F_MATCH\n\n // NEW request flags\n static let NLM_F_REPLACE: UInt16 = 0x100\n static let NLM_F_EXCL: UInt16 = 0x200\n static let NLM_F_CREATE: UInt16 = 0x400\n static let NLM_F_APPEND: UInt16 = 0x800\n}\n\nstruct NetlinkScope {\n static let RT_SCOPE_UNIVERSE: UInt8 = 0\n}\n\nstruct InterfaceFlags {\n static let IFF_UP: UInt32 = 1 << 0\n static let DEFAULT_CHANGE: UInt32 = 0xffff_ffff\n}\n\nstruct LinkAttributeType {\n static let IFLA_EXT_IFNAME: UInt16 = 3\n static let IFLA_MTU: UInt16 = 4\n static let IFLA_EXT_MASK: UInt16 = 29\n}\n\nstruct LinkAttributeMaskFilter {\n static let RTEXT_FILTER_VF: UInt32 = 1 << 0\n static let RTEXT_FILTER_SKIP_STATS: UInt32 = 1 << 3\n}\n\nstruct AddressAttributeType {\n // subnet mask\n static let IFA_ADDRESS: UInt16 = 1\n // IPv4 address\n static let IFA_LOCAL: UInt16 = 2\n}\n\nstruct RouteTable {\n static let MAIN: UInt8 = 254\n}\n\nstruct RouteProtocol {\n static let UNSPEC: UInt8 = 0\n static let REDIRECT: UInt8 = 1\n static let KERNEL: UInt8 = 2\n static let BOOT: UInt8 = 3\n static let STATIC: UInt8 = 4\n}\n\nstruct RouteScope {\n static let UNIVERSE: UInt8 = 0\n static let LINK: UInt8 = 253\n}\n\nstruct RouteType {\n static let UNSPEC: UInt8 = 0\n static let UNICAST: UInt8 = 1\n}\n\nstruct RouteAttributeType {\n static let UNSPEC: UInt16 = 0\n static let DST: UInt16 = 1\n static let SRC: UInt16 = 2\n static let IIF: UInt16 = 3\n static let OIF: UInt16 = 4\n static let GATEWAY: UInt16 = 5\n static let PRIORITY: UInt16 = 6\n static let PREFSRC: UInt16 = 7\n}\n\nprotocol Bindable: Equatable {\n static var size: Int { get }\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int\n}\n\nstruct SockaddrNetlink: Bindable {\n static let size = 12\n\n var family: UInt16\n var pad: UInt16 = 0\n var pid: UInt32\n var groups: UInt32\n\n init(family: UInt16 = 0, pid: UInt32 = 0, groups: UInt32 = 0) {\n self.family = family\n self.pid = pid\n self.groups = groups\n }\n\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let offset = buffer.copyIn(as: UInt16.self, value: family, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: pid, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: groups, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n family = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n pid = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n groups = value\n\n return offset + Self.size\n }\n}\n\nstruct NetlinkMessageHeader: Bindable {\n static let size = 16\n\n var len: UInt32\n var type: UInt16\n var flags: UInt16\n var seq: UInt32\n var pid: UInt32\n\n init(len: UInt32 = 0, type: UInt16 = 0, flags: UInt16 = 0, seq: UInt32? = nil, pid: UInt32 = 0) {\n self.len = len\n self.type = type\n self.flags = flags\n self.seq = seq ?? UInt32.random(in: 0.. Int {\n guard let offset = buffer.copyIn(as: UInt32.self, value: len, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt16.self, value: type, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt16.self, value: flags, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: seq, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: pid, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n len = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n type = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n flags = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n seq = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n pid = value\n\n return offset\n }\n\n var moreResponses: Bool {\n (self.flags & NetlinkFlags.NLM_F_MULTI) != 0\n && (self.type != NetlinkType.NLMSG_DONE && self.type != NetlinkType.NLMSG_ERROR\n && self.type != NetlinkType.NLMSG_OVERRUN)\n }\n}\n\nstruct InterfaceInfo: Bindable {\n static let size = 16\n\n var family: UInt8\n var _pad: UInt8 = 0\n var type: UInt16\n var index: Int32\n var flags: UInt32\n var change: UInt32\n\n init(\n family: UInt8 = UInt8(AddressFamily.AF_UNSPEC), type: UInt16 = 0, index: Int32 = 0, flags: UInt32 = 0,\n change: UInt32 = 0\n ) {\n self.family = family\n self.type = type\n self.index = index\n self.flags = flags\n self.change = change\n }\n\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let offset = buffer.copyIn(as: UInt8.self, value: family, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: _pad, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt16.self, value: type, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: Int32.self, value: index, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: flags, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: change, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n family = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n _pad = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n type = value\n\n guard let (offset, value) = buffer.copyOut(as: Int32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n index = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n flags = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n change = value\n\n return offset\n }\n}\n\nstruct AddressInfo: Bindable {\n static let size = 8\n\n var family: UInt8\n var prefixLength: UInt8\n var flags: UInt8\n var scope: UInt8\n var index: UInt32\n\n init(\n family: UInt8 = UInt8(AddressFamily.AF_UNSPEC), prefixLength: UInt8 = 32, flags: UInt8 = 0, scope: UInt8 = 0,\n index: UInt32 = 0\n ) {\n self.family = family\n self.prefixLength = prefixLength\n self.flags = flags\n self.scope = scope\n self.index = index\n }\n\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let offset = buffer.copyIn(as: UInt8.self, value: family, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: prefixLength, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: flags, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: scope, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: index, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n family = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n prefixLength = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n flags = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n scope = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n index = value\n\n return offset\n }\n}\n\nstruct RouteInfo: Bindable {\n static let size = 12\n\n var family: UInt8\n var dstLen: UInt8\n var srcLen: UInt8\n var tos: UInt8\n var table: UInt8\n var proto: UInt8\n var scope: UInt8\n var type: UInt8\n var flags: UInt32\n\n init(\n family: UInt8 = UInt8(AddressFamily.AF_INET),\n dstLen: UInt8,\n srcLen: UInt8,\n tos: UInt8,\n table: UInt8,\n proto: UInt8,\n scope: UInt8,\n type: UInt8,\n flags: UInt32\n ) {\n self.family = family\n self.dstLen = dstLen\n self.srcLen = srcLen\n self.tos = tos\n self.table = table\n self.proto = proto\n self.scope = scope\n self.type = type\n self.flags = flags\n }\n\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let offset = buffer.copyIn(as: UInt8.self, value: family, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: dstLen, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: srcLen, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: tos, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: table, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: proto, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: scope, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt8.self, value: type, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt32.self, value: flags, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n family = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n dstLen = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n srcLen = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n tos = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n table = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n proto = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n scope = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt8.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n type = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt32.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n flags = value\n\n return offset\n }\n}\n\n/// A route information.\npublic struct RTAttribute: Bindable {\n static let size = 4\n\n public var len: UInt16\n public var type: UInt16\n public var paddedLen: Int { Int(((len + 3) >> 2) << 2) }\n\n init(len: UInt16 = 0, type: UInt16 = 0) {\n self.len = len\n self.type = type\n }\n\n func appendBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let offset = buffer.copyIn(as: UInt16.self, value: len, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n guard let offset = buffer.copyIn(as: UInt16.self, value: type, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n\n return offset\n }\n\n mutating func bindBuffer(_ buffer: inout [UInt8], offset: Int) throws -> Int {\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n len = value\n\n guard let (offset, value) = buffer.copyOut(as: UInt16.self, offset: offset) else {\n throw NetlinkDataError.sendMarshalFailure\n }\n type = value\n\n return offset\n }\n}\n\n/// A route information with data.\npublic struct RTAttributeData {\n public let attribute: RTAttribute\n public let data: [UInt8]\n}\n\n/// A response from the get link command.\npublic struct LinkResponse {\n public let interfaceIndex: Int32\n public let attrDatas: [RTAttributeData]\n}\n\n/// Errors thrown when parsing netlink data.\npublic enum NetlinkDataError: Swift.Error, CustomStringConvertible, Equatable {\n case sendMarshalFailure\n case recvUnmarshalFailure\n case responseError(rc: Int32)\n case unsupportedPlatform\n\n /// The description of the errors.\n public var description: String {\n switch self {\n case .sendMarshalFailure:\n return \"could not marshal netlink packet\"\n case .recvUnmarshalFailure:\n return \"could not unmarshal netlink packet\"\n case .responseError(let rc):\n return \"netlink response indicates error, rc = \\(rc)\"\n case .unsupportedPlatform:\n return \"unsupported platform\"\n }\n }\n}\n"], ["/containerization/Sources/cctl/LoginCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\nextension Application {\n struct Login: AsyncParsableCommand {\n\n static let configuration = CommandConfiguration(\n commandName: \"login\",\n abstract: \"Login to a registry\"\n )\n\n @OptionGroup() var application: Application\n\n @Option(name: .shortAndLong, help: \"Username\")\n var username: String = \"\"\n\n @Flag(help: \"Take the password from stdin\")\n var passwordStdin: Bool = false\n\n @Argument(help: \"Registry server name\")\n var server: String\n\n @Flag(help: \"Use plain text http to authenticate\") var http: Bool = false\n\n func run() async throws {\n var username = self.username\n var password = \"\"\n if passwordStdin {\n if username == \"\" {\n throw ContainerizationError(.invalidArgument, message: \"must provide --username with --password-stdin\")\n }\n guard let passwordData = try FileHandle.standardInput.readToEnd() else {\n throw ContainerizationError(.invalidArgument, message: \"failed to read password from stdin\")\n }\n password = String(decoding: passwordData, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)\n }\n let keychain = KeychainHelper(id: Application.keychainID)\n if username == \"\" {\n username = try keychain.userPrompt(domain: server)\n }\n if password == \"\" {\n password = try keychain.passwordPrompt()\n print()\n }\n\n let server = Reference.resolveDomain(domain: self.server)\n let scheme = http ? \"http\" : \"https\"\n let client = RegistryClient(\n host: server,\n scheme: scheme,\n authentication: BasicAuthentication(username: username, password: password),\n retryOptions: .init(\n maxRetries: 10,\n retryInterval: 300_000_000,\n shouldRetry: ({ response in\n response.status.code >= 500\n })\n )\n )\n try await client.ping()\n try keychain.save(domain: server, username: username, password: password)\n print(\"Login succeeded\")\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Path.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// `Path` provides utilities to look for binaries in the current PATH,\n/// or to return the current PATH.\npublic struct Path {\n /// lookPath looks up an executable's path from $PATH\n public static func lookPath(_ name: String) -> URL? {\n lookup(name, path: getPath())\n }\n\n // getEnv returns the default environment of the process\n // with the default $PATH added for the context of a macOS application bundle\n public static func getEnv() -> [String: String] {\n var env = ProcessInfo.processInfo.environment\n env[\"PATH\"] = getPath()\n return env\n }\n\n private static func lookup(_ name: String, path: String) -> URL? {\n if name.contains(\"/\") {\n if findExec(name) {\n return URL(fileURLWithPath: name)\n }\n return nil\n }\n\n for var lookdir in path.split(separator: \":\") {\n if lookdir.isEmpty {\n lookdir = \".\"\n }\n let file = URL(fileURLWithPath: String(lookdir)).appendingPathComponent(name)\n if findExec(file.path) {\n return file\n }\n }\n return nil\n }\n\n /// getPath returns $PATH for the current process\n private static func getPath() -> String {\n let env = ProcessInfo.processInfo.environment\n return env[\"PATH\"] ?? \"/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin\"\n }\n\n // findPath returns a string containing the 'PATH' environment variable\n private static func findPath(_ env: [String]) -> String? {\n env.first(where: { path in\n let split = path.split(separator: \"=\")\n return split.count == 2 && split[0] == \"PATH\"\n })\n }\n\n // findExec returns true if the provided path is an executable\n private static func findExec(_ path: String) -> Bool {\n let fm = FileManager.default\n return fm.isExecutableFile(atPath: path)\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension EXT4.InodeFlag {\n public static func | (lhs: Self, rhs: Self) -> Self {\n Self(rawValue: lhs.rawValue | rhs.rawValue)\n }\n\n public static func | (lhs: Self, rhs: Self) -> UInt32 {\n lhs.rawValue | rhs.rawValue\n }\n\n public static func | (lhs: Self, rhs: UInt32) -> UInt32 {\n lhs.rawValue | rhs\n }\n}\n\nextension EXT4.CompatFeature {\n public static func | (lhs: Self, rhs: Self) -> Self {\n EXT4.CompatFeature(rawValue: lhs.rawValue | rhs.rawValue)\n }\n\n public static func | (lhs: Self, rhs: Self) -> UInt32 {\n lhs.rawValue | rhs.rawValue\n }\n}\n\nextension EXT4.IncompatFeature {\n public static func | (lhs: Self, rhs: Self) -> Self {\n EXT4.IncompatFeature(rawValue: lhs.rawValue | rhs.rawValue)\n }\n\n public static func | (lhs: Self, rhs: Self) -> UInt32 {\n lhs.rawValue | rhs.rawValue\n }\n}\n\nextension EXT4.RoCompatFeature {\n public static func | (lhs: Self, rhs: Self) -> Self {\n EXT4.RoCompatFeature(rawValue: lhs.rawValue | rhs.rawValue)\n }\n\n public static func | (lhs: Self, rhs: Self) -> UInt32 {\n lhs.rawValue | rhs.rawValue\n }\n}\n\nextension EXT4.FileModeFlag {\n public static func | (lhs: Self, rhs: Self) -> Self {\n Self(rawValue: lhs.rawValue | rhs.rawValue)\n }\n\n public static func | (lhs: Self, rhs: Self) -> UInt16 {\n lhs.rawValue | rhs.rawValue\n }\n}\n\nextension EXT4.XAttrEntry {\n init(using bytes: [UInt8]) throws {\n guard bytes.count == 16 else {\n throw EXT4.Error.invalidXattrEntry\n }\n nameLength = bytes[0]\n nameIndex = bytes[1]\n let rawValue = Array(bytes[2...3])\n valueOffset = UInt16(littleEndian: rawValue.withUnsafeBytes { $0.load(as: UInt16.self) })\n\n let rawValueInum = Array(bytes[4...7])\n valueInum = UInt32(littleEndian: rawValueInum.withUnsafeBytes { $0.load(as: UInt32.self) })\n\n let rawSize = Array(bytes[8...11])\n valueSize = UInt32(littleEndian: rawSize.withUnsafeBytes { $0.load(as: UInt32.self) })\n\n let rawHash = Array(bytes[12...])\n hash = UInt32(littleEndian: rawHash.withUnsafeBytes { $0.load(as: UInt32.self) })\n }\n}\n\nextension EXT4 {\n static func tupleToArray(_ tuple: T) -> [UInt8] {\n let reflection = Mirror(reflecting: tuple)\n return reflection.children.compactMap { $0.value as? UInt8 }\n }\n}\n"], ["/containerization/Sources/cctl/KernelCommand.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport Foundation\n\nextension Application {\n struct KernelCommand: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: \"kernel\",\n abstract: \"Manage kernel images\",\n subcommands: [\n Create.self\n ]\n )\n\n struct Create: AsyncParsableCommand {\n @Option(name: .shortAndLong, help: \"Name for the kernel image\")\n var name: String\n\n @Option(name: .long, help: \"Labels to add to the built image of the form =, [=,...]\")\n var labels: [String] = []\n\n @Argument var kernels: [String]\n\n func run() async throws {\n let imageStore = Application.imageStore\n let contentStore = Application.contentStore\n let labels = Application.parseKeyValuePairs(from: labels)\n let binaries = try parseBinaries()\n _ = try await KernelImage.create(\n reference: name,\n binaries: binaries,\n labels: labels,\n imageStore: imageStore,\n contentStore: contentStore\n )\n }\n\n func parseBinaries() throws -> [Kernel] {\n var binaries = [Kernel]()\n for rawBinary in kernels {\n let parts = rawBinary.split(separator: \":\")\n guard parts.count == 2 else {\n throw \"Invalid binary format: \\(rawBinary)\"\n }\n let platform: SystemPlatform\n switch parts[1] {\n case \"arm64\":\n platform = .linuxArm\n case \"amd64\":\n platform = .linuxAmd\n default:\n fatalError(\"unsupported platform \\(parts[1])\")\n }\n binaries.append(\n .init(\n path: URL(fileURLWithPath: String(parts[0])),\n platform: platform\n )\n )\n }\n return binaries\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/AsyncLock.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// `AsyncLock` provides a familiar locking API, with the main benefit being that it\n/// is safe to call async methods while holding the lock. This is primarily used in spots\n/// where an actor makes sense, but we may need to ensure we don't fall victim to actor\n/// reentrancy issues.\npublic actor AsyncLock {\n private var busy = false\n private var queue: ArraySlice> = []\n\n public struct Context: Sendable {\n fileprivate init() {}\n }\n\n public init() {}\n\n /// withLock provides a scoped locking API to run a function while holding the lock.\n public func withLock(_ body: @Sendable @escaping (Context) async throws -> T) async rethrows -> T {\n while self.busy {\n await withCheckedContinuation { cc in\n self.queue.append(cc)\n }\n }\n\n self.busy = true\n\n defer {\n self.busy = false\n if let next = self.queue.popFirst() {\n next.resume(returning: ())\n } else {\n self.queue = []\n }\n }\n\n let context = Context()\n return try await body(context)\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Bundle.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Foundation\n\n#if canImport(Musl)\nimport Musl\nprivate let _mount = Musl.mount\nprivate let _umount = Musl.umount2\n#elseif canImport(Glibc)\nimport Glibc\nprivate let _mount = Glibc.mount\nprivate let _umount = Glibc.umount2\n#endif\n\n/// `Bundle` represents an OCI runtime spec bundle for running\n/// a container.\npublic struct Bundle: Sendable {\n /// The path to the bundle.\n public let path: URL\n\n /// The path to the OCI runtime spec config.json file.\n public var configPath: URL {\n self.path.appending(path: \"config.json\")\n }\n\n /// The path to a rootfs mount inside the bundle.\n public var rootfsPath: URL {\n self.path.appending(path: \"rootfs\")\n }\n\n /// Create the OCI bundle.\n ///\n /// - Parameters:\n /// - path: A URL pointing to where to create the bundle on the filesystem.\n /// - spec: A data blob that should contain an OCI runtime spec. This will be written\n /// to the bundle as a \"config.json\" file.\n public static func create(path: URL, spec: Data) throws -> Bundle {\n try self.init(path: path, spec: spec)\n }\n\n /// Create the OCI bundle.\n ///\n /// - Parameters:\n /// - path: A URL pointing to where to create the bundle on the filesystem.\n /// - spec: An OCI runtime spec that will be written to the bundle as a \"config.json\"\n /// file.\n public static func create(path: URL, spec: ContainerizationOCI.Spec) throws -> Bundle {\n try self.init(path: path, spec: spec)\n }\n\n /// Load an OCI bundle from the provided path.\n ///\n /// - Parameters:\n /// - path: A URL pointing to where to load the bundle from on the filesystem.\n public static func load(path: URL) throws -> Bundle {\n try self.init(path: path)\n }\n\n private init(path: URL) throws {\n let fm = FileManager.default\n if !fm.fileExists(atPath: path.path) {\n throw ContainerizationError(.invalidArgument, message: \"no bundle at \\(path.path)\")\n }\n self.path = path\n }\n\n // This constructor does not do any validation that data is actually a\n // valid OCI spec.\n private init(path: URL, spec: Data) throws {\n self.path = path\n\n let fm = FileManager.default\n try fm.createDirectory(\n atPath: self.path.appending(component: \"rootfs\").path,\n withIntermediateDirectories: true\n )\n\n try spec.write(to: self.configPath)\n }\n\n private init(path: URL, spec: ContainerizationOCI.Spec) throws {\n self.path = path\n\n let fm = FileManager.default\n try fm.createDirectory(\n atPath: self.path.appending(component: \"rootfs\").path,\n withIntermediateDirectories: true\n )\n\n let specData = try JSONEncoder().encode(spec)\n try specData.write(to: self.configPath)\n }\n\n /// Delete the OCI bundle from the filesystem.\n public func delete() throws {\n // Unmount, and then blow away the dir.\n #if os(Linux)\n let rootfs = self.rootfsPath.path\n guard _umount(rootfs, 0) == 0 else {\n throw POSIXError.fromErrno()\n }\n #endif\n // removeItem is recursive so should blow away the rootfs dir inside as well.\n let fm = FileManager.default\n try fm.removeItem(at: self.path)\n }\n\n /// Load and return the OCI runtime spec written to the bundle.\n public func loadConfig() throws -> ContainerizationOCI.Spec {\n let data = try Data(contentsOf: self.configPath)\n return try JSONDecoder().decode(ContainerizationOCI.Spec.self, from: data)\n }\n}\n"], ["/containerization/Sources/SendablePropertyMacros/SendablePropertyMacro.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SwiftCompilerPlugin\nimport SwiftParser\nimport SwiftSyntax\nimport SwiftSyntaxBuilder\nimport SwiftSyntaxMacros\n\n/// A macro that allows to make a property of a supported type thread-safe keeping the `Sendable` conformance of the type.\npublic struct SendablePropertyMacro: PeerMacro {\n private static let allowedTypes: Set = [\n \"Int\", \"UInt\", \"Int16\", \"UInt16\", \"Int32\", \"UInt32\", \"Int64\", \"UInt64\", \"Float\", \"Double\", \"Bool\", \"UnsafeRawPointer\", \"UnsafeMutableRawPointer\", \"UnsafePointer\",\n \"UnsafeMutablePointer\",\n ]\n\n private static func checkPropertyType(in declaration: some DeclSyntaxProtocol) throws {\n guard let varDecl = declaration.as(VariableDeclSyntax.self),\n let binding = varDecl.bindings.first,\n let typeAnnotation = binding.typeAnnotation,\n let id = typeAnnotation.type.as(IdentifierTypeSyntax.self)\n else {\n // Nothing to check.\n return\n }\n\n var typeName = id.name.text\n // Allow optionals of the allowed types.\n if typeName.prefix(9) == \"Optional<\" && typeName.suffix(1) == \">\" {\n typeName = String(typeName.dropFirst(9).dropLast(1))\n }\n // Allow generics of the allowed types.\n if typeName.contains(\"<\") {\n typeName = String(typeName.prefix { $0 != \"<\" })\n }\n\n guard allowedTypes.contains(typeName) else {\n throw SendablePropertyError.notApplicableToType\n }\n }\n\n /// The macro expansion that introduces a `Sendable`-conforming \"peer\" declaration for a thread-safe storage for the value of the given declaration of a variable.\n /// - Parameters:\n /// - node: The given attribute node.\n /// - declaration: The given declaration.\n /// - context: The macro expansion context.\n public static func expansion(\n of node: SwiftSyntax.AttributeSyntax, providingPeersOf declaration: some SwiftSyntax.DeclSyntaxProtocol, in context: some SwiftSyntaxMacros.MacroExpansionContext\n ) throws -> [SwiftSyntax.DeclSyntax] {\n try checkPropertyType(in: declaration)\n return try SendablePropertyMacroUnchecked.expansion(of: node, providingPeersOf: declaration, in: context)\n }\n}\n\nextension SendablePropertyMacro: AccessorMacro {\n /// The macro expansion that adds `Sendable`-conforming accessors to the given declaration of a variable.\n /// - Parameters:\n /// - node: The given attribute node.\n /// - declaration: The given declaration.\n /// - context: The macro expansion context.\n public static func expansion(\n of node: SwiftSyntax.AttributeSyntax, providingAccessorsOf declaration: some SwiftSyntax.DeclSyntaxProtocol, in context: some SwiftSyntaxMacros.MacroExpansionContext\n ) throws -> [SwiftSyntax.AccessorDeclSyntax] {\n try checkPropertyType(in: declaration)\n return try SendablePropertyMacroUnchecked.expansion(of: node, providingAccessorsOf: declaration, in: context)\n }\n}\n"], ["/containerization/Sources/ContainerizationIO/ReadStream.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport NIO\n\n/// `ReadStream` is a utility type for streaming data from a `URL`\n/// or `Data` blob.\npublic class ReadStream {\n public static let bufferSize = Int(1.mib())\n\n private var _stream: InputStream\n private let _buffSize: Int\n private let _data: Data?\n private let _url: URL?\n\n public init() {\n _stream = InputStream(data: .init())\n _buffSize = Self.bufferSize\n self._data = Data()\n self._url = nil\n }\n\n public init(url: URL, bufferSize: Int = bufferSize) throws {\n guard FileManager.default.fileExists(atPath: url.path) else {\n throw Error.noSuchFileOrDirectory(url)\n }\n guard let stream = InputStream(url: url) else {\n throw Error.failedToCreateStream\n }\n self._stream = stream\n self._buffSize = bufferSize\n self._url = url\n self._data = nil\n }\n\n public init(data: Data, bufferSize: Int = bufferSize) {\n self._stream = InputStream(data: data)\n self._buffSize = bufferSize\n self._url = nil\n self._data = data\n }\n\n /// Resets the read stream. This either reassigns\n /// the data buffer or url to a new InputStream internally.\n public func reset() throws {\n self._stream.close()\n if let url = self._url {\n guard let s = InputStream(url: url) else {\n throw Error.failedToCreateStream\n }\n self._stream = s\n return\n }\n let data = self._data ?? Data()\n self._stream = InputStream(data: data)\n }\n\n /// Get access to an `AsyncStream` of `ByteBuffer`'s from the input source.\n public var stream: AsyncStream {\n AsyncStream { cont in\n self._stream.open()\n defer { self._stream.close() }\n\n let readBuffer = UnsafeMutablePointer.allocate(capacity: _buffSize)\n\n while true {\n let byteRead = self._stream.read(readBuffer, maxLength: _buffSize)\n if byteRead <= 0 {\n readBuffer.deallocate()\n cont.finish()\n break\n } else {\n let data = Data(bytes: readBuffer, count: byteRead)\n let buffer = ByteBuffer(bytes: data)\n cont.yield(buffer)\n }\n }\n }\n }\n\n /// Get access to an `AsyncStream` of `Data` objects from the input source.\n public var dataStream: AsyncStream {\n AsyncStream { cont in\n self._stream.open()\n defer { self._stream.close() }\n\n let readBuffer = UnsafeMutablePointer.allocate(capacity: self._buffSize)\n while true {\n let byteRead = self._stream.read(readBuffer, maxLength: self._buffSize)\n if byteRead <= 0 {\n readBuffer.deallocate()\n cont.finish()\n break\n } else {\n let data = Data(bytes: readBuffer, count: byteRead)\n cont.yield(data)\n }\n }\n }\n }\n}\n\nextension ReadStream {\n /// Errors that can be encountered while using a `ReadStream`.\n public enum Error: Swift.Error, CustomStringConvertible {\n case failedToCreateStream\n case noSuchFileOrDirectory(_ p: URL)\n\n public var description: String {\n switch self {\n case .failedToCreateStream:\n return \"failed to create stream\"\n case .noSuchFileOrDirectory(let p):\n return \"no such file or directory: \\(p.path)\"\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Linux/Binfmt.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n#if canImport(Musl)\nimport Musl\nprivate let _mount = Musl.mount\n#elseif canImport(Glibc)\nimport Glibc\nprivate let _mount = Glibc.mount\n#endif\n\n/// `Binfmt` is a utility type that contains static helpers and types for\n/// mounting the Linux binfmt_misc filesystem, and creating new binfmt entries.\npublic struct Binfmt: Sendable {\n /// Default mount path for binfmt_misc.\n public static let path = \"/proc/sys/fs/binfmt_misc\"\n\n /// Entry models a binfmt_misc entry.\n /// https://docs.kernel.org/admin-guide/binfmt-misc.html\n public struct Entry {\n public var name: String\n public var type: String\n public var offset: String\n public var magic: String\n public var mask: String\n public var flags: String\n\n public init(\n name: String,\n type: String = \"M\",\n offset: String = \"\",\n magic: String,\n mask: String,\n flags: String = \"CF\"\n ) {\n self.name = name\n self.type = type\n self.offset = offset\n self.magic = magic\n self.mask = mask\n self.flags = flags\n }\n\n /// Returns a binfmt `Entry` for amd64 ELF binaries.\n public static func amd64() -> Self {\n Binfmt.Entry(\n name: \"x86_64\",\n magic: #\"\\x7fELF\\x02\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x3e\\x00\"#,\n mask: #\"\\xff\\xff\\xff\\xff\\xff\\xfe\\xfe\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff\"#\n )\n }\n\n #if os(Linux)\n /// Register the passed in `binaryPath` as the interpreter for a new binfmt_misc entry.\n public func register(binaryPath: String) throws {\n let registration = \":\\(self.name):\\(self.type):\\(self.offset):\\(self.magic):\\(self.mask):\\(binaryPath):\\(self.flags)\"\n\n try registration.write(\n to: URL(fileURLWithPath: Binfmt.path).appendingPathComponent(\"register\"),\n atomically: false,\n encoding: .ascii\n )\n }\n\n /// Deregister the binfmt_misc entry described by the current object.\n public func deregister() throws {\n let data = \"-1\"\n try data.write(\n to: URL(fileURLWithPath: Binfmt.path).appendingPathComponent(self.name),\n atomically: false,\n encoding: .ascii\n )\n }\n #endif // os(Linux)\n }\n\n #if os(Linux)\n /// Crude check to see if /proc/sys/fs/binfmt_misc/register exists.\n public static func mounted() -> Bool {\n FileManager.default.fileExists(atPath: \"\\(Self.path)/register\")\n }\n\n /// Mount the binfmt_misc filesystem.\n public static func mount() throws {\n guard _mount(\"binfmt_misc\", Self.path, \"binfmt_misc\", 0, \"\") == 0 else {\n throw POSIXError.fromErrno()\n }\n }\n #endif // os(Linux)\n}\n"], ["/containerization/Sources/Containerization/VirtualMachineInstance.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// The runtime state of the virtual machine instance.\npublic enum VirtualMachineInstanceState: Sendable {\n case starting\n case running\n case stopped\n case stopping\n case unknown\n}\n\n/// A live instance of a virtual machine.\npublic protocol VirtualMachineInstance: Sendable {\n associatedtype Agent: VirtualMachineAgent\n\n // The state of the virtual machine.\n var state: VirtualMachineInstanceState { get }\n\n var mounts: [AttachedFilesystem] { get }\n /// Dial the Agent. It's up the VirtualMachineInstance to determine\n /// what port the agent is listening on.\n func dialAgent() async throws -> Agent\n /// Dial a vsock port in the guest.\n func dial(_ port: UInt32) async throws -> FileHandle\n /// Listen on a host vsock port.\n func listen(_ port: UInt32) throws -> VsockConnectionStream\n /// Stop listening on a vsock port.\n func stopListen(_ port: UInt32) throws\n /// Start the virtual machine.\n func start() async throws\n /// Stop the virtual machine.\n func stop() async throws\n}\n"], ["/containerization/Sources/Containerization/TimeSyncer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Logging\n\nactor TimeSyncer: Sendable {\n private var task: Task?\n private var context: Vminitd?\n private let logger: Logger?\n\n init(logger: Logger?) {\n self.logger = logger\n }\n\n func start(context: Vminitd, interval: Duration = .seconds(30)) {\n precondition(task == nil, \"time syncer is already running\")\n self.context = context\n self.task = Task {\n while true {\n do {\n do {\n try await Task.sleep(for: interval)\n } catch {\n return\n }\n\n var timeval = timeval()\n guard gettimeofday(&timeval, nil) == 0 else {\n throw POSIXError.fromErrno()\n }\n\n try await context.setTime(\n sec: Int64(timeval.tv_sec),\n usec: Int32(timeval.tv_usec)\n )\n } catch {\n self.logger?.error(\"failed to sync time with guest agent: \\(error)\")\n }\n }\n }\n }\n\n func close() async throws {\n guard let task else {\n preconditionFailure(\"time syncer was already closed\")\n }\n\n task.cancel()\n try await self.context?.close()\n self.task = nil\n self.context = nil\n }\n}\n"], ["/containerization/Sources/Containerization/DNSConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// DNS configuration for a container. The values will be used to\n/// construct /etc/resolv.conf for a given container.\npublic struct DNS: Sendable {\n /// The set of default nameservers to use if none are provided\n /// in the constructor.\n public static let defaultNameservers = [\"1.1.1.1\"]\n\n /// The nameservers a container should use.\n public var nameservers: [String]\n /// The DNS domain to use.\n public var domain: String?\n /// The DNS search domains to use.\n public var searchDomains: [String]\n /// The DNS options to use.\n public var options: [String]\n\n public init(\n nameservers: [String] = defaultNameservers,\n domain: String? = nil,\n searchDomains: [String] = [],\n options: [String] = []\n ) {\n self.nameservers = nameservers\n self.domain = domain\n self.searchDomains = searchDomains\n self.options = options\n }\n}\n\nextension DNS {\n public var resolvConf: String {\n var text = \"\"\n\n if !nameservers.isEmpty {\n text += nameservers.map { \"nameserver \\($0)\" }.joined(separator: \"\\n\") + \"\\n\"\n }\n\n if let domain {\n text += \"domain \\(domain)\\n\"\n }\n\n if !searchDomains.isEmpty {\n text += \"search \\(searchDomains.joined(separator: \" \"))\\n\"\n }\n\n if !options.isEmpty {\n text += \"opts \\(options.joined(separator: \" \"))\\n\"\n }\n\n return text\n }\n}\n"], ["/containerization/Sources/Containerization/AttachedFilesystem.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport ContainerizationOCI\n\n/// A filesystem that was attached and able to be mounted inside the runtime environment.\npublic struct AttachedFilesystem: Sendable {\n /// The type of the filesystem.\n public var type: String\n /// The path to the filesystem within a sandbox.\n public var source: String\n /// Destination when mounting the filesystem inside a sandbox.\n public var destination: String\n /// The options to use when mounting the filesystem.\n public var options: [String]\n\n #if os(macOS)\n public init(mount: Mount, allocator: any AddressAllocator) throws {\n switch mount.type {\n case \"virtiofs\":\n let name = try hashMountSource(source: mount.source)\n self.source = name\n case \"ext4\":\n let char = try allocator.allocate()\n self.source = \"/dev/vd\\(char)\"\n default:\n self.source = mount.source\n }\n self.type = mount.type\n self.options = mount.options\n self.destination = mount.destination\n }\n #endif\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+FileTree.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\nextension EXT4 {\n class FileTree {\n class FileTreeNode {\n let inode: InodeNumber\n let name: String\n var children: [Ptr] = []\n var blocks: (start: UInt32, end: UInt32)?\n var additionalBlocks: [(start: UInt32, end: UInt32)]?\n var link: InodeNumber?\n private var parent: Ptr?\n\n init(\n inode: InodeNumber,\n name: String,\n parent: Ptr?,\n children: [Ptr] = [],\n blocks: (start: UInt32, end: UInt32)? = nil,\n additionalBlocks: [(start: UInt32, end: UInt32)]? = nil,\n link: InodeNumber? = nil\n ) {\n self.inode = inode\n self.name = name\n self.children = children\n self.blocks = blocks\n self.additionalBlocks = additionalBlocks\n self.link = link\n self.parent = parent\n }\n\n deinit {\n self.children.removeAll()\n self.children = []\n self.blocks = nil\n self.additionalBlocks = nil\n self.link = nil\n }\n\n var path: FilePath? {\n var components: [String] = [self.name]\n var _ptr = self.parent\n while let ptr = _ptr {\n components.append(ptr.pointee.name)\n _ptr = ptr.pointee.parent\n }\n guard let last = components.last else {\n return nil\n }\n guard components.count > 1 else {\n return FilePath(last)\n }\n components = components.dropLast()\n let path = components.reversed().joined(separator: \"/\")\n guard let data = path.data(using: .utf8) else {\n return nil\n }\n guard let dataPath = String(data: data, encoding: .utf8) else {\n return nil\n }\n return FilePath(dataPath).pushing(FilePath(last)).lexicallyNormalized()\n }\n }\n\n var root: Ptr\n\n init(_ root: InodeNumber, _ name: String) {\n self.root = Ptr.allocate(capacity: 1)\n self.root.initialize(to: FileTreeNode(inode: root, name: name, parent: nil))\n }\n\n func lookup(path: FilePath) -> Ptr? {\n var components: [String] = path.items\n var node = self.root\n if components.first == \"/\" {\n components = Array(components.dropFirst())\n }\n if components.count == 0 {\n return node\n }\n for component in components {\n var found = false\n for childPtr in node.pointee.children {\n let child = childPtr.pointee\n if child.name == component {\n node = childPtr\n found = true\n break\n }\n }\n guard found else {\n return nil\n }\n }\n return node\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/URL+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// The `resolvingSymlinksInPath` method of the `URL` struct does not resolve the symlinks\n/// for directories under `/private` which include`tmp`, `var` and `etc`\n/// hence adding a method to build up on the existing `resolvingSymlinksInPath` that prepends `/private` to those paths\nextension URL {\n /// returns the unescaped absolutePath of a URL joined by separator\n func absolutePath(_ separator: String = \"/\") -> String {\n self.pathComponents\n .joined(separator: separator)\n .dropFirst(\"/\".count)\n .description\n }\n\n public func resolvingSymlinksInPathWithPrivate() -> URL {\n let url = self.resolvingSymlinksInPath()\n #if os(macOS)\n let parts = url.pathComponents\n if parts.count > 1 {\n if (parts.first == \"/\") && [\"tmp\", \"var\", \"etc\"].contains(parts[1]) {\n if let resolved = NSURL.fileURL(withPathComponents: [\"/\", \"private\"] + parts[1...]) {\n return resolved\n }\n }\n }\n #endif\n return url\n }\n\n public var isDirectory: Bool {\n (try? resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true\n }\n\n public var isSymlink: Bool {\n (try? resourceValues(forKeys: [.isSymbolicLinkKey]))?.isSymbolicLink == true\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/ProcessSupervisor.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\nimport Logging\n\nactor ProcessSupervisor {\n private let queue: DispatchQueue\n // `DispatchSourceSignal` is thread-safe.\n private nonisolated(unsafe) let source: DispatchSourceSignal\n private var processes = [ManagedProcess]()\n\n var log: Logger?\n\n func setLog(_ log: Logger?) {\n self.log = log\n }\n\n static let `default` = ProcessSupervisor()\n\n let poller: Epoll\n\n private init() {\n let queue = DispatchQueue(label: \"process-supervisor\")\n self.source = DispatchSource.makeSignalSource(signal: SIGCHLD, queue: queue)\n self.queue = queue\n self.poller = try! Epoll()\n let t = Thread {\n try! self.poller.run()\n }\n t.start()\n }\n\n func ready() {\n self.source.setEventHandler {\n do {\n self.log?.debug(\"received SIGCHLD, reaping processes\")\n try self.handleSignal()\n } catch {\n self.log?.error(\"reaping processes failed\", metadata: [\"error\": \"\\(error)\"])\n }\n }\n self.source.resume()\n }\n\n private func handleSignal() throws {\n dispatchPrecondition(condition: .onQueue(queue))\n\n self.log?.debug(\"starting to wait4 processes\")\n let exited = Reaper.reap()\n self.log?.debug(\"finished wait4 of \\(exited.count) processes\")\n\n self.log?.debug(\"checking for exit of managed process\", metadata: [\"exits\": \"\\(exited)\", \"processes\": \"\\(processes.count)\"])\n let exitedProcesses = self.processes.filter { proc in\n exited.contains { pid, _ in\n proc.pid == pid\n }\n }\n\n for proc in exitedProcesses {\n let pid = proc.pid\n if pid <= 0 {\n continue\n }\n\n if let status = exited[pid] {\n self.log?.debug(\n \"managed process exited\",\n metadata: [\n \"pid\": \"\\(pid)\",\n \"status\": \"\\(status)\",\n \"count\": \"\\(processes.count - 1)\",\n ])\n proc.setExit(status)\n self.processes.removeAll(where: { $0.pid == pid })\n }\n }\n }\n\n func start(process: ManagedProcess) throws -> Int32 {\n self.log?.debug(\"in supervisor lock to start process\")\n defer {\n self.log?.debug(\"out of supervisor lock to start process\")\n }\n\n do {\n self.processes.append(process)\n return try process.start()\n } catch {\n self.log?.error(\"process start failed \\(error)\", metadata: [\"process-id\": \"\\(process.id)\"])\n throw error\n }\n }\n\n deinit {\n self.log?.info(\"process supervisor deinit\")\n source.cancel()\n }\n}\n"], ["/containerization/vminitd/Sources/vmexec/Mount.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOCI\nimport ContainerizationOS\nimport Foundation\nimport Musl\n\nstruct ContainerMount {\n private let mounts: [ContainerizationOCI.Mount]\n private let rootfs: String\n\n init(rootfs: String, mounts: [ContainerizationOCI.Mount]) {\n self.rootfs = rootfs\n self.mounts = mounts\n }\n\n func mountToRootfs() throws {\n for m in self.mounts {\n let osMount = m.toOSMount()\n try osMount.mount(root: self.rootfs)\n }\n }\n\n func configureConsole() throws {\n let ptmx = self.rootfs.standardizingPath.appendingPathComponent(\"/dev/ptmx\")\n\n guard remove(ptmx) == 0 else {\n throw App.Errno(stage: \"remove(ptmx)\")\n }\n guard symlink(\"pts/ptmx\", ptmx) == 0 else {\n throw App.Errno(stage: \"symlink(pts/ptmx)\")\n }\n }\n\n private func mkdirAll(_ name: String, _ perm: Int16) throws {\n try FileManager.default.createDirectory(\n atPath: name,\n withIntermediateDirectories: true,\n attributes: [.posixPermissions: perm]\n )\n }\n}\n\nextension ContainerizationOCI.Mount {\n func toOSMount() -> ContainerizationOS.Mount {\n ContainerizationOS.Mount(\n type: self.type,\n source: self.source,\n target: self.destination,\n options: self.options\n )\n }\n}\n"], ["/containerization/Sources/ContainerizationNetlink/NetlinkSocket.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A protocol for interacting with a netlink socket.\npublic protocol NetlinkSocket {\n var pid: UInt32 { get }\n func send(buf: UnsafeRawPointer!, len: Int, flags: Int32) throws -> Int\n func recv(buf: UnsafeMutableRawPointer!, len: Int, flags: Int32) throws -> Int\n}\n\n/// A netlink socket provider.\npublic typealias NetlinkSocketProvider = () throws -> any NetlinkSocket\n\n/// Errors thrown when interacting with a netlink socket.\npublic enum NetlinkSocketError: Swift.Error, CustomStringConvertible, Equatable {\n case socketFailure(rc: Int32)\n case bindFailure(rc: Int32)\n case sendFailure(rc: Int32)\n case recvFailure(rc: Int32)\n case notImplemented\n\n /// The description of the errors.\n public var description: String {\n switch self {\n case .socketFailure(let rc):\n return \"could not create netlink socket, rc = \\(rc)\"\n case .bindFailure(let rc):\n return \"could not bind netlink socket, rc = \\(rc)\"\n case .sendFailure(let rc):\n return \"could not send netlink packet, rc = \\(rc)\"\n case .recvFailure(let rc):\n return \"could not receive netlink packet, rc = \\(rc)\"\n case .notImplemented:\n return \"socket function not implemented for platform\"\n }\n }\n}\n\n#if canImport(Musl)\nimport Musl\nlet osSocket = Musl.socket\nlet osBind = Musl.bind\nlet osSend = Musl.send\nlet osRecv = Musl.recv\n\n/// A default implementation of `NetlinkSocket`.\npublic class DefaultNetlinkSocket: NetlinkSocket {\n private let sockfd: Int32\n\n /// The process identifier of the process creating this socket.\n public let pid: UInt32\n\n /// Creates a new instance.\n public init() throws {\n pid = UInt32(getpid())\n sockfd = osSocket(Int32(AddressFamily.AF_NETLINK), SocketType.SOCK_RAW, NetlinkProtocol.NETLINK_ROUTE)\n guard sockfd >= 0 else {\n throw NetlinkSocketError.socketFailure(rc: errno)\n }\n\n let addr = SockaddrNetlink(family: AddressFamily.AF_NETLINK, pid: pid)\n var buffer = [UInt8](repeating: 0, count: SockaddrNetlink.size)\n _ = try addr.appendBuffer(&buffer, offset: 0)\n guard let ptr = buffer.bind(as: sockaddr.self, size: buffer.count) else {\n throw NetlinkSocketError.bindFailure(rc: 0)\n }\n guard osBind(sockfd, ptr, UInt32(buffer.count)) >= 0 else {\n throw NetlinkSocketError.bindFailure(rc: errno)\n }\n }\n\n deinit {\n close(sockfd)\n }\n\n /// Sends a request to a netlink socket.\n /// Returns the number of bytes sent.\n /// - Parameters:\n /// - buf: The buffer to send.\n /// - len: The length of the buffer to send.\n /// - flags: The send flags.\n public func send(buf: UnsafeRawPointer!, len: Int, flags: Int32) throws -> Int {\n let count = osSend(sockfd, buf, len, flags)\n guard count >= 0 else {\n throw NetlinkSocketError.sendFailure(rc: errno)\n }\n\n return count\n }\n\n /// Receives a response from a netlink socket.\n /// Returns the number of bytes received.\n /// - Parameters:\n /// - buf: The buffer to receive into.\n /// - len: The maximum number of bytes to receive.\n /// - flags: The receive flags.\n public func recv(buf: UnsafeMutableRawPointer!, len: Int, flags: Int32) throws -> Int {\n let count = osRecv(sockfd, buf, len, flags)\n guard count >= 0 else {\n throw NetlinkSocketError.recvFailure(rc: errno)\n }\n\n return count\n }\n}\n#else\npublic class DefaultNetlinkSocket: NetlinkSocket {\n public var pid: UInt32 { 0 }\n\n public init() throws {}\n\n public func send(buf: UnsafeRawPointer!, len: Int, flags: Int32) throws -> Int {\n throw NetlinkSocketError.notImplemented\n }\n\n public func recv(buf: UnsafeMutableRawPointer!, len: Int, flags: Int32) throws -> Int {\n throw NetlinkSocketError.notImplemented\n }\n}\n#endif\n"], ["/containerization/Sources/ContainerizationOCI/Client/RegistryClient+Error.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport AsyncHTTPClient\nimport Foundation\nimport NIOHTTP1\n\nextension RegistryClient {\n /// `RegistryClient` errors.\n public enum Error: Swift.Error, CustomStringConvertible {\n case invalidStatus(url: String, HTTPResponseStatus, reason: String? = nil)\n\n /// Description of the errors.\n public var description: String {\n switch self {\n case .invalidStatus(let u, let response, let reason):\n return \"HTTP request to \\(u) failed with response: \\(response.description). Reason: \\(reason ?? \"Unknown\")\"\n }\n }\n }\n\n /// The container registry typically returns actionable failure reasons in the response body\n /// of the failing HTTP Request. This type models the structure of the error message.\n /// Reference: https://distribution.github.io/distribution/spec/api/#errors\n internal struct ErrorResponse: Codable {\n let errors: [RemoteError]\n\n internal struct RemoteError: Codable {\n let code: String\n let message: String\n let detail: String?\n }\n\n internal static func fromResponseBody(_ body: HTTPClientResponse.Body) async -> ErrorResponse? {\n guard var buffer = try? await body.collect(upTo: Int(1.mib())) else {\n return nil\n }\n guard let bytes = buffer.readBytes(length: buffer.readableBytes) else {\n return nil\n }\n let data = Data(bytes)\n guard let jsonError = try? JSONDecoder().decode(ErrorResponse.self, from: data) else {\n return nil\n }\n return jsonError\n }\n\n public var jsonString: String {\n let data = try? JSONEncoder().encode(self)\n guard let data else {\n return \"{}\"\n }\n return String(data: data, encoding: .utf8) ?? \"{}\"\n }\n }\n}\n"], ["/containerization/Sources/Containerization/Hash.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if os(macOS)\n\nimport Crypto\nimport ContainerizationError\n\nfunc hashMountSource(source: String) throws -> String {\n guard let data = source.data(using: .utf8) else {\n throw ContainerizationError(.invalidArgument, message: \"\\(source) could not be converted to Data\")\n }\n return String(SHA256.hash(data: data).encoded.prefix(36))\n}\n\n#endif\n"], ["/containerization/Sources/cctl/cctl+Utils.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Containerization\nimport ContainerizationError\nimport ContainerizationOCI\nimport Foundation\n\nextension Application {\n static func fetchImage(reference: String, store: ImageStore) async throws -> Containerization.Image {\n do {\n return try await store.get(reference: reference)\n } catch let error as ContainerizationError {\n if error.code == .notFound {\n return try await store.pull(reference: reference)\n }\n throw error\n }\n }\n\n static func parseKeyValuePairs(from items: [String]) -> [String: String] {\n var parsedLabels: [String: String] = [:]\n for item in items {\n let parts = item.split(separator: \"=\", maxSplits: 1)\n guard parts.count == 2 else {\n continue\n }\n let key = String(parts[0])\n let val = String(parts[1])\n parsedLabels[key] = val\n }\n return parsedLabels\n }\n}\n\nextension ContainerizationOCI.Platform {\n static var arm64: ContainerizationOCI.Platform {\n .init(arch: \"arm64\", os: \"linux\", variant: \"v8\")\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/URL+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension URL {\n /// Returns the unescaped absolutePath of a URL joined by separator.\n public func absolutePath() -> String {\n #if os(macOS)\n return self.path(percentEncoded: false)\n #else\n return self.path\n #endif\n }\n\n /// Returns the domain name of a registry.\n public var domain: String? {\n guard let host = self.absoluteString.split(separator: \":\").first else {\n return nil\n }\n return String(host)\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\n\n/**\n ```\n# EXT4 Filesystem Layout\n\n The EXT4 filesystem divides the disk into an upfront metadata section followed by several logical groups known as block groups. The\n metadata section looks like this:\n\n +--------------------------+\n | Boot Sector (1024) |\n +--------------------------+\n | Superblock (1024) |\n +--------------------------+\n | Empty (2048) |\n +--------------------------+\n | |\n | [Block Group Descriptors]|\n | |\n | - Free/used block bitmap |\n | - Free/used inode bitmap |\n | - Inode table pointer |\n | - Other metadata |\n | |\n +--------------------------+\n\n ## Block Groups\n\n Each block group optionally stores a copy of the superblock and group descriptor table for disaster recovery.\n The rest of the block group comprises of data blocks. The size of each block group is dynamically decided\n while formatting, based on total amount of space available on the disk.\n\n +--------------------------+\n | Block Group 0 |\n | +------------------+ |\n | | Super Block | |\n | +------------------+ |\n | | Group Desc. | |\n | +------------------+ |\n | | Data Blocks | |\n | | | |\n | +------------------+ |\n +--------------------------+\n | Block Group 1 |\n | +------------------+ |\n | | Super Block | |\n | +------------------+ |\n | | Group Desc. | |\n | +------------------+ |\n | | Data Blocks | |\n | | | |\n | +------------------+ |\n +--------------------------+\n | ... |\n +--------------------------+\n | Block Group N |\n | +------------------+ |\n | | Super Block | |\n | +------------------+ |\n | | Group Desc. | |\n | +------------------+ |\n | | Data Blocks | |\n | | | |\n | +------------------+ |\n +--------------------------+\n\n The descriptor for each block group contain the following information:\n\n - Block Bitmap\n - Inode Bitmap\n - Pointer to Inode Table\n - other metadata such as used block count, num. dirs etc.\n\n ### Block Bitmap\n\n A sequence of bits, where each bit represents a block in the block group.\n\n 1: In use block\n 0: Free block\n\n +---------------+---------------+\n | Block |\n | Bitmap |\n +---------------+---------------+\n | 1 0 1 0 1 1 0 0 |\n +---------------+---------------+\n | | | | | | | |\n | | | | | | | |\n v v v v v v v v\n +---+---+---+---+---+---+---+---+\n | B | | B | | B | B | | |\n +---+---+---+---+---+---+---+---+\n\n Whenever a file is created, free data blocks are identified by using this table.\n When it is deleted, the corresponding data blocks are marked as free.\n\n ### Inode Bitmap\n\n A sequence of bits, where each bit represents a inode in the block group. Since\n inodes per group is a fixed number, this bitmap is made to be of sufficient length\n to accommodate that many inodes\n\n 1: In use inode\n 0: Free inode\n\n +---------------+---------------+\n | Inode |\n | Bitmap |\n +---------------+---------------+\n | 1 0 1 0 1 1 0 0 |\n +---------------+---------------+\n | | | | | | | |\n | | | | | | | |\n v v v v v v v v\n +---+---+---+---+---+---+---+---+\n | I | | I | | I | I | | |\n +---+---+---+---+---+---+---+---+\n\n ## Inode table\n\n Inode table provides a mapping from Inode -> Data blocks. In this implementation, inode size is set to 256 bytes.\n Inode table uses extents to efficiently describe the mapping.\n\n +-----------------------+\n | Inode Table |\n +-----------------------+\n | Inode | Metadata |\n +-------+---------------+\n | 1 | permissions |\n | | size |\n | | user ID |\n | | group ID |\n | | timestamps |\n | | block |\n | | blocks count |\n +-------+---------------+\n | 2 | ... |\n +-------+---------------+\n | ... | ... |\n +-------+---------------+\n\n The length of `block` field in the inode table is 60 bytes. This field contains an extent tree\n that holds information about ranges of blocks used by the file. For smaller files, the entire extent\n tree can be stored within this field.\n\n +-----------------------+\n | Inode |\n +-----------------------+\n | Metadata |\n +-----------------------+\n | Extent Tree |\n | +-------------------+ |\n | | Extent Leaf Node | |\n | +-------------------+ |\n | | - Start Block | |\n | | - Block Count | |\n | | - ... | |\n | +-------------------+ |\n +-----------------------+\n\n For larger files which span across multiple non-contiguous blocks, extent tree's root points to extent\n blocks, which in-turn point to the blocks used by the file\n\n +-----------------------+\n | Extent Tree |\n | +-------------------+ |\n | | Extent Root | |\n | +-------------------+ |\n | | - Pointers to | |\n | | Extent Blocks | |\n | +-------------------+ |\n +-----------------------+\n |\n v\n +-----------------------+\n | Extent Block |\n +-----------------------+\n | +-------------------+ |\n | | Extent Leaf Node | |\n | +-------------------+ |\n | | - Start Block | |\n | | - Block Count | |\n | | - ... | |\n | +-------------------+ |\n | +-------------------+ |\n | | Extent Leaf Node | |\n | +-------------------+ |\n | | - Start Block | |\n | | - Block Count | |\n | | - ... | |\n | +-------------------+ |\n +-----------------------+\n\n ## Directory entries\n\n The data blocks for directory inodes point to a list of directory entrees. Each entry\n consists of only a name and inode number. The name and inode number correspond to the\n name and inode number of the children of the directory\n\n +-------------------------+\n | Directory Entry |\n +-------------------------+\n | inode | rec_len | name |\n +-------------------------+\n | 2 | 1 | \".\" |\n +-------------------------+\n | Directory Entry |\n +-------------------------+\n | inode | rec_len | name |\n +-------------------------+\n | 1 | 2 | \"..\" |\n +-------------------------+\n | Directory Entry |\n +-------------------------+\n | inode | rec_len | name |\n +-------------------------+\n | 11 | 10 | lost& |\n | | | found |\n +-------------------------+\n\nMore details can be found here https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout\n\n```\n*/\n\n/// A type for interacting with ext4 file systems.\n///\n/// The `Ext4` class provides functionality to read the superblock of an existing ext4 block device\n/// and format a new block device with the ext4 file system.\n///\n/// Usage:\n/// - To read the superblock of an existing ext4 block device, create an instance of `Ext4` with the\n/// path to the block device\n/// - To format a new block device with ext4, create an instance of `Ext4.Formatter` with the path to the block\n/// device and call the `close()` method.\n///\n/// Example 1: Read an existing block device\n/// ```swift\n/// let blockDevice = URL(filePath: \"/dev/sdb\")\n/// // succeeds if a valid ext4 fs is found at path\n/// let ext4 = try Ext4(blockDevice: blockDevice)\n/// print(\"Block size: \\(ext4.blockSize)\")\n/// print(\"Total size: \\(ext4.size)\")\n///\n/// // Reading the superblock\n/// let superblock = ext4.superblock\n/// print(\"Superblock information:\")\n/// print(\"Total blocks: \\(superblock.blocksCountLow)\")\n/// ```\n///\n/// Example 2: Format a new block device (Refer [`EXT4.Formatter`](x-source-tag://EXT4.Formatter) for more info)\n/// ```swift\n/// let devicePath = URL(filePath: \"/dev/sdc\")\n/// let formatter = try EXT4.Formatter(devicePath, blockSize: 4096)\n/// try formatter.close()\n/// ```\npublic enum EXT4 {\n public static let SuperBlockMagic: UInt16 = 0xef53\n\n static let ExtentHeaderMagic: UInt16 = 0xf30a\n static let XAttrHeaderMagic: UInt32 = 0xea02_0000\n\n static let DefectiveBlockInode: InodeNumber = 1\n static let RootInode: InodeNumber = 2\n static let FirstInode: InodeNumber = 11\n static let LostAndFoundInode: InodeNumber = 11\n\n static let InodeActualSize: UInt32 = 160 // 160 bytes used by metadata\n static let InodeExtraSize: UInt32 = 96 // 96 bytes for inline xattrs\n static let InodeSize: UInt32 = UInt32(MemoryLayout.size) // 256 bytes. This is the max size of an inode\n static let XattrInodeHeaderSize: UInt32 = 4\n static let XattrBlockHeaderSize: UInt32 = 32\n static let ExtraIsize: UInt16 = UInt16(InodeActualSize) - 128\n\n static let MaxLinks: UInt32 = 65000\n static let MaxBlocksPerExtent: UInt32 = 0x8000\n static let MaxFileSize: UInt64 = 128.gib()\n static let SuperBlockOffset: UInt64 = 1024\n}\n\nextension EXT4 {\n // `EXT4` errors.\n public enum Error: Swift.Error, CustomStringConvertible, Sendable, Equatable {\n case notFound(_ path: String)\n case couldNotReadSuperBlock(_ path: String, _ offset: UInt64, _ size: Int)\n case invalidSuperBlock\n case deepExtentsUnimplemented\n case invalidExtents\n case invalidXattrEntry\n case couldNotReadBlock(_ block: UInt32)\n case invalidPathEncoding(_ path: String)\n case couldNotReadInode(_ inode: UInt32)\n case couldNotReadGroup(_ group: UInt32)\n public var description: String {\n switch self {\n case .notFound(let path):\n return \"file at path \\(path) not found\"\n case .couldNotReadSuperBlock(let path, let offset, let size):\n return \"could not read \\(size) bytes of superblock from \\(path) at offset \\(offset)\"\n case .invalidSuperBlock:\n return \"not a valid EXT4 superblock\"\n case .deepExtentsUnimplemented:\n return \"deep extents are not supported\"\n case .invalidExtents:\n return \"extents invalid or corrupted\"\n case .invalidXattrEntry:\n return \"invalid extended attribute entry\"\n case .couldNotReadBlock(let block):\n return \"could not read block \\(block)\"\n case .invalidPathEncoding(let path):\n return \"path encoding for '\\(path)' is invalid, must be ascii or utf8\"\n case .couldNotReadInode(let inode):\n return \"could not read inode \\(inode)\"\n case .couldNotReadGroup(let group):\n return \"could not read group descriptor \\(group)\"\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Sysctl.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Helper type to deal with system control functionalities.\npublic struct Sysctl {\n #if os(macOS)\n /// Simple `sysctlbyname` wrapper.\n public static func byName(_ name: String) throws -> Int64 {\n var num: Int64 = 0\n var size = MemoryLayout.size\n if sysctlbyname(name, &num, &size, nil, 0) != 0 {\n throw POSIXError.fromErrno()\n }\n return num\n }\n #endif\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/LocalContent.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Crypto\nimport Foundation\n\npublic final class LocalContent: Content {\n public let path: URL\n private let file: FileHandle\n\n public init(path: URL) throws {\n guard FileManager.default.fileExists(atPath: path.path) else {\n throw ContainerizationError(.notFound, message: \"Content at path \\(path.absolutePath())\")\n }\n\n self.file = try FileHandle(forReadingFrom: path)\n self.path = path\n }\n\n public func digest() throws -> SHA256.Digest {\n let bufferSize = 64 * 1024 // 64 KB\n var hasher = SHA256()\n\n try self.file.seek(toOffset: 0)\n while case let data = file.readData(ofLength: bufferSize), !data.isEmpty {\n hasher.update(data: data)\n }\n\n let digest = hasher.finalize()\n\n try self.file.seek(toOffset: 0)\n return digest\n }\n\n public func data(offset: UInt64 = 0, length size: Int = 0) throws -> Data? {\n try file.seek(toOffset: offset)\n if size == 0 {\n return try file.readToEnd()\n }\n return try file.read(upToCount: size)\n }\n\n public func data() throws -> Data {\n try Data(contentsOf: self.path)\n }\n\n public func size() throws -> UInt64 {\n let fileAttrs = try FileManager.default.attributesOfItem(atPath: self.path.absolutePath())\n if let size = fileAttrs[FileAttributeKey.size] as? UInt64 {\n return size\n }\n throw ContainerizationError(.internalError, message: \"Could not determine file size for \\(path.absolutePath())\")\n }\n\n public func decode() throws -> T where T: Decodable {\n let json = JSONDecoder()\n let data = try Data(contentsOf: self.path)\n return try json.decode(T.self, from: data)\n }\n\n deinit {\n try? self.file.close()\n }\n}\n"], ["/containerization/Sources/Containerization/Agent/Vminitd+Rosetta.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\n\nextension Vminitd {\n /// Enable Rosetta's x86_64 emulation.\n public func enableRosetta() async throws {\n let path = \"/run/rosetta\"\n try await self.mount(\n .init(\n type: \"virtiofs\",\n source: \"rosetta\",\n destination: path\n )\n )\n try await self.setupEmulator(\n binaryPath: \"\\(path)/rosetta\",\n configuration: Binfmt.Entry.amd64()\n )\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/File.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Trivial type to discover information about a given file (uid, gid, mode...).\npublic struct File: Sendable {\n /// `File` errors.\n public enum Error: Swift.Error, CustomStringConvertible {\n case errno(_ e: Int32)\n\n public var description: String {\n switch self {\n case .errno(let code):\n return \"errno \\(code)\"\n }\n }\n }\n\n /// Returns a `FileInfo` struct with information about the file.\n /// - Parameters:\n /// - url: The path to the file.\n public static func info(_ url: URL) throws -> FileInfo {\n try info(url.path)\n }\n\n /// Returns a `FileInfo` struct with information about the file.\n /// - Parameters:\n /// - path: The path to the file as a string.\n public static func info(_ path: String) throws -> FileInfo {\n var st = stat()\n guard stat(path, &st) == 0 else {\n throw Error.errno(errno)\n }\n return FileInfo(path, stat: st)\n }\n}\n\n/// `FileInfo` holds and provides easy access to stat(2) data\n/// for a file.\npublic struct FileInfo: Sendable {\n private let _stat_t: Foundation.stat\n private let _path: String\n\n init(_ path: String, stat: stat) {\n self._path = path\n self._stat_t = stat\n }\n\n /// mode_t for the file.\n public var mode: mode_t {\n self._stat_t.st_mode\n }\n\n /// The files uid.\n public var uid: Int {\n Int(self._stat_t.st_uid)\n }\n\n /// The files gid.\n public var gid: Int {\n Int(self._stat_t.st_gid)\n }\n\n /// The filesystem ID the file belongs to.\n public var dev: Int {\n Int(self._stat_t.st_dev)\n }\n\n /// The files inode number.\n public var ino: Int {\n Int(self._stat_t.st_ino)\n }\n\n /// The size of the file.\n public var size: Int {\n Int(self._stat_t.st_size)\n }\n\n /// The path to the file.\n public var path: String {\n self._path\n }\n\n /// Returns if the file is a directory.\n public var isDirectory: Bool {\n mode & S_IFMT == S_IFDIR\n }\n\n /// Returns if the file is a pipe.\n public var isPipe: Bool {\n mode & S_IFMT == S_IFIFO\n }\n\n /// Returns if the file is a socket.\n public var isSocket: Bool {\n mode & S_IFMT == S_IFSOCK\n }\n\n /// Returns if the file is a link.\n public var isLink: Bool {\n mode & S_IFMT == S_IFLNK\n }\n\n /// Returns if the file is a regular file.\n public var isRegularFile: Bool {\n mode & S_IFMT == S_IFREG\n }\n\n /// Returns if the file is a block device.\n public var isBlock: Bool {\n mode & S_IFMT == S_IFBLK\n }\n\n /// Returns if the file is a character device.\n public var isChar: Bool {\n mode & S_IFMT == S_IFCHR\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/ArchiveError.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport CArchive\nimport Foundation\n\n/// An enumeration of the errors that can be thrown while interacting with an archive.\npublic enum ArchiveError: Error, CustomStringConvertible {\n case unableToCreateArchive\n case noUnderlyingArchive\n case noArchiveInCallback\n case noDelegateConfigured\n case delegateFreedBeforeCallback\n case unableToSetFormat(CInt, Format)\n case unableToAddFilter(CInt, Filter)\n case unableToWriteEntryHeader(CInt)\n case unableToWriteData(CLong)\n case unableToCloseArchive(CInt)\n case unableToOpenArchive(CInt)\n case unableToSetOption(CInt)\n case failedToSetLocale(locales: [String])\n case failedToGetProperty(String, URLResourceKey)\n case failedToDetectFilter\n case failedToDetectFormat\n case failedToExtractArchive(String)\n\n /// Description of the error\n public var description: String {\n switch self {\n case .unableToCreateArchive:\n return \"Unable to create an archive.\"\n case .noUnderlyingArchive:\n return \"No underlying archive was provided.\"\n case .noArchiveInCallback:\n return \"No archive was provided in the callback.\"\n case .noDelegateConfigured:\n return \"No delegate was configured.\"\n case .delegateFreedBeforeCallback:\n return \"The delegate was freed before the callback was invoked.\"\n case .unableToSetFormat(let code, let name):\n return \"Unable to set the archive format \\(name), code \\(code)\"\n case .unableToAddFilter(let code, let name):\n return \"Unable to set the archive filter \\(name), code \\(code)\"\n case .unableToWriteEntryHeader(let code):\n return \"Unable to write the entry header to the archive. Error code \\(code)\"\n case .unableToWriteData(let code):\n return \"Unable to write data to the archive. Error code \\(code)\"\n case .unableToCloseArchive(let code):\n return \"Unable to close the archive. Error code \\(code)\"\n case .unableToOpenArchive(let code):\n return \"Unable to open the archive. Error code \\(code)\"\n case .unableToSetOption(_):\n return \"Unable to set an option on the archive.\"\n case .failedToSetLocale(let locales):\n return \"Failed to set locale to \\(locales)\"\n case .failedToGetProperty(let path, let propertyName):\n return \"Failed to read property \\(propertyName) from file at path \\(path)\"\n case .failedToDetectFilter:\n return \"Failed to detect filter from archive.\"\n case .failedToDetectFormat:\n return \"Failed to detect format from archive.\"\n case .failedToExtractArchive(let reason):\n return \"Failed to extract archive: \\(reason)\"\n }\n }\n}\n\npublic struct LibArchiveError: Error {\n public let source: ArchiveError\n public let description: String\n}\n\nfunc wrap(_ f: @autoclosure () -> CInt, _ e: (CInt) -> ArchiveError, underlying: OpaquePointer? = nil) throws {\n let result = f()\n guard result == ARCHIVE_OK else {\n let error = e(result)\n guard let underlying = underlying,\n let description = archive_error_string(underlying).map(String.init(cString:))\n else {\n throw error\n }\n throw LibArchiveError(source: error, description: description)\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Manifest.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// Source: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/manifest.go\n\nimport Foundation\n\n/// Manifest provides `application/vnd.oci.image.manifest.v1+json` mediatype structure when marshalled to JSON.\npublic struct Manifest: Codable, Sendable {\n /// `schemaVersion` is the image manifest schema that this image follows.\n public let schemaVersion: Int\n\n /// `mediaType` specifies the type of this document data structure, e.g. `application/vnd.oci.image.manifest.v1+json`.\n public let mediaType: String?\n\n /// `config` references a configuration object for a container, by digest.\n /// The referenced configuration object is a JSON blob that the runtime uses to set up the container.\n public let config: Descriptor\n\n /// `layers` is an indexed list of layers referenced by the manifest.\n public let layers: [Descriptor]\n\n /// `annotations` contains arbitrary metadata for the image manifest.\n public let annotations: [String: String]?\n\n public init(\n schemaVersion: Int = 2, mediaType: String = MediaTypes.imageManifest, config: Descriptor, layers: [Descriptor],\n annotations: [String: String]? = nil\n ) {\n self.schemaVersion = schemaVersion\n self.mediaType = mediaType\n self.config = config\n self.layers = layers\n self.annotations = annotations\n }\n}\n"], ["/containerization/Sources/cctl/cctl.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Containerization\nimport ContainerizationOCI\nimport Foundation\nimport Logging\n\nlet log = {\n LoggingSystem.bootstrap(StreamLogHandler.standardError)\n var log = Logger(label: \"com.apple.containerization\")\n log.logLevel = .debug\n return log\n}()\n\n@main\nstruct Application: AsyncParsableCommand {\n static let keychainID = \"com.apple.containerization\"\n static let appRoot: URL = {\n FileManager.default.urls(\n for: .applicationSupportDirectory,\n in: .userDomainMask\n ).first!\n .appendingPathComponent(\"com.apple.containerization\")\n }()\n\n private static let _contentStore: ContentStore = {\n try! LocalContentStore(path: appRoot.appendingPathComponent(\"content\"))\n }()\n\n private static let _imageStore: ImageStore = {\n try! ImageStore(\n path: appRoot,\n contentStore: contentStore\n )\n }()\n\n static var imageStore: ImageStore {\n _imageStore\n }\n\n static var contentStore: ContentStore {\n _contentStore\n }\n\n static let configuration = CommandConfiguration(\n commandName: \"cctl\",\n abstract: \"Utility CLI for Containerization\",\n version: \"2.0.0\",\n subcommands: [\n Images.self,\n Login.self,\n Rootfs.self,\n Run.self,\n ]\n )\n}\n\nextension String {\n var absoluteURL: URL {\n URL(fileURLWithPath: self).absoluteURL\n }\n}\n\nextension String: Swift.Error {\n\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/ContentWriter.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationError\nimport Crypto\nimport Foundation\nimport NIOCore\n\n/// Provides a context to write data into a directory.\npublic class ContentWriter {\n private let base: URL\n private let encoder = JSONEncoder()\n\n /// Create a new ContentWriter.\n /// - Parameters:\n /// - base: The URL to write content to. If this is not a directory a\n /// ContainerizationError will be thrown with a code of .internalError.\n public init(for base: URL) throws {\n self.encoder.outputFormatting = [JSONEncoder.OutputFormatting.sortedKeys]\n\n self.base = base\n var isDirectory = ObjCBool(true)\n let exists = FileManager.default.fileExists(atPath: base.path, isDirectory: &isDirectory)\n\n guard exists && isDirectory.boolValue else {\n throw ContainerizationError(.internalError, message: \"Cannot create ContentWriter for path \\(base.absolutePath()). Not a directory\")\n }\n }\n\n /// Writes the data blob to the base URL provided in the constructor.\n /// - Parameters:\n /// - data: The data blob to write to a file under the base path.\n @discardableResult\n public func write(_ data: Data) throws -> (size: Int64, digest: SHA256.Digest) {\n let digest = SHA256.hash(data: data)\n let destination = base.appendingPathComponent(digest.encoded)\n try data.write(to: destination)\n return (Int64(data.count), digest)\n }\n\n /// Reads the data present in the passed in URL and writes it to the base path.\n /// - Parameters:\n /// - url: The URL to read the data from.\n @discardableResult\n public func create(from url: URL) throws -> (size: Int64, digest: SHA256.Digest) {\n let data = try Data(contentsOf: url)\n return try self.write(data)\n }\n\n /// Encodes the passed in type as a JSON blob and writes it to the base path.\n /// - Parameters:\n /// - content: The type to convert to JSON.\n @discardableResult\n public func create(from content: T) throws -> (size: Int64, digest: SHA256.Digest) {\n let data = try self.encoder.encode(content)\n return try self.write(data)\n }\n}\n"], ["/containerization/Sources/Containerization/Kernel.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// An object representing a Linux kernel used to boot a virtual machine.\n/// In addition to a path to the kernel itself, this type stores relevant\n/// data such as the commandline to pass to the kernel, and init arguments.\npublic struct Kernel: Sendable, Codable {\n /// The command line arguments passed to the kernel on boot.\n public struct CommandLine: Sendable, Codable {\n public static let kernelDefaults = [\n \"console=hvc0\",\n \"tsc=reliable\",\n ]\n\n /// Adds the debug argument to the kernel commandline.\n mutating public func addDebug() {\n self.kernelArgs.append(\"debug\")\n }\n\n /// Adds a panic level to the kernel commandline.\n mutating public func addPanic(level: Int) {\n self.kernelArgs.append(\"panic=\\(level)\")\n }\n\n /// Additional kernel arguments.\n public var kernelArgs: [String]\n /// Additional arguments passed to the Initial Process / Agent.\n public var initArgs: [String]\n\n /// Initializes the kernel commandline using the mix of kernel arguments\n /// and init arguments.\n public init(\n kernelArgs: [String] = kernelDefaults,\n initArgs: [String] = []\n ) {\n self.kernelArgs = kernelArgs\n self.initArgs = initArgs\n }\n\n /// Initializes the kernel commandline to the defaults of Self.kernelDefaults,\n /// adds a debug and panic flag as instructed, and optionally a set of init\n /// process flags to supply to vminitd.\n public init(debug: Bool, panic: Int, initArgs: [String] = []) {\n var args = Self.kernelDefaults\n if debug {\n args.append(\"debug\")\n }\n args.append(\"panic=\\(panic)\")\n self.kernelArgs = args\n self.initArgs = initArgs\n }\n }\n\n /// Path on disk to the kernel binary.\n public var path: URL\n /// Platform for the kernel.\n public var platform: SystemPlatform\n /// Kernel and init process command line.\n public var commandLine: Self.CommandLine\n\n /// Kernel command line arguments.\n public var kernelArgs: [String] {\n self.commandLine.kernelArgs\n }\n\n /// Init process arguments.\n public var initArgs: [String] {\n self.commandLine.initArgs\n }\n\n public init(\n path: URL,\n platform: SystemPlatform,\n commandline: Self.CommandLine = CommandLine(debug: false, panic: 0)\n ) {\n self.path = path\n self.platform = platform\n self.commandLine = commandline\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Types.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// swiftlint:disable large_tuple\n\nimport Foundation\n\nextension EXT4 {\n public struct SuperBlock {\n public var inodesCount: UInt32 = 0\n public var blocksCountLow: UInt32 = 0\n public var rootBlocksCountLow: UInt32 = 0\n public var freeBlocksCountLow: UInt32 = 0\n public var freeInodesCount: UInt32 = 0\n public var firstDataBlock: UInt32 = 0\n public var logBlockSize: UInt32 = 0\n public var logClusterSize: UInt32 = 0\n public var blocksPerGroup: UInt32 = 0\n public var clustersPerGroup: UInt32 = 0\n public var inodesPerGroup: UInt32 = 0\n public var mtime: UInt32 = 0\n public var wtime: UInt32 = 0\n public var mountCount: UInt16 = 0\n public var maxMountCount: UInt16 = 0\n public var magic: UInt16 = 0\n public var state: UInt16 = 0\n public var errors: UInt16 = 0\n public var minorRevisionLevel: UInt16 = 0\n public var lastCheck: UInt32 = 0\n public var checkInterval: UInt32 = 0\n public var creatorOS: UInt32 = 0\n public var revisionLevel: UInt32 = 0\n public var defaultReservedUid: UInt16 = 0\n public var defaultReservedGid: UInt16 = 0\n public var firstInode: UInt32 = 0\n public var inodeSize: UInt16 = 0\n public var blockGroupNr: UInt16 = 0\n public var featureCompat: UInt32 = 0\n public var featureIncompat: UInt32 = 0\n public var featureRoCompat: UInt32 = 0\n public var uuid:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var volumeName:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var lastMounted:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var algorithmUsageBitmap: UInt32 = 0\n public var preallocBlocks: UInt8 = 0\n public var preallocDirBlocks: UInt8 = 0\n public var reservedGdtBlocks: UInt16 = 0\n public var journalUUID:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var journalInum: UInt32 = 0\n public var journalDev: UInt32 = 0\n public var lastOrphan: UInt32 = 0\n public var hashSeed: (UInt32, UInt32, UInt32, UInt32) = (0, 0, 0, 0)\n public var defHashVersion: UInt8 = 0\n public var journalBackupType: UInt8 = 0\n public var descSize: UInt16 = UInt16(MemoryLayout.size)\n public var defaultMountOpts: UInt32 = 0\n public var firstMetaBg: UInt32 = 0\n public var mkfsTime: UInt32 = 0\n public var journalBlocks:\n (\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0\n )\n public var blocksCountHigh: UInt32 = 0\n public var rBlocksCountHigh: UInt32 = 0\n public var freeBlocksCountHigh: UInt32 = 0\n public var minExtraIsize: UInt16 = 0\n public var wantExtraIsize: UInt16 = 0\n public var flags: UInt32 = 0\n public var raidStride: UInt16 = 0\n public var mmpInterval: UInt16 = 0\n public var mmpBlock: UInt64 = 0\n public var raidStripeWidth: UInt32 = 0\n public var logGroupsPerFlex: UInt8 = 0\n public var checksumType: UInt8 = 0\n public var reservedPad: UInt16 = 0\n public var kbytesWritten: UInt64 = 0\n public var snapshotInum: UInt32 = 0\n public var snapshotID: UInt32 = 0\n public var snapshotRBlocksCount: UInt64 = 0\n public var snapshotList: UInt32 = 0\n public var errorCount: UInt32 = 0\n public var firstErrorTime: UInt32 = 0\n public var firstErrorInode: UInt32 = 0\n public var firstErrorBlock: UInt64 = 0\n public var firstErrorFunc:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var firstErrorLine: UInt32 = 0\n public var lastErrorTime: UInt32 = 0\n public var lastErrorInode: UInt32 = 0\n public var lastErrorLine: UInt32 = 0\n public var lastErrorBlock: UInt64 = 0\n public var lastErrorFunc:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var mountOpts:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var userQuotaInum: UInt32 = 0\n public var groupQuotaInum: UInt32 = 0\n public var overheadBlocks: UInt32 = 0\n public var backupBgs: (UInt32, UInt32) = (0, 0)\n public var encryptAlgos: (UInt8, UInt8, UInt8, UInt8) = (0, 0, 0, 0)\n public var encryptPwSalt:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var lpfInode: UInt32 = 0\n public var projectQuotaInum: UInt32 = 0\n public var checksumSeed: UInt32 = 0\n public var wtimeHigh: UInt8 = 0\n public var mtimeHigh: UInt8 = 0\n public var mkfsTimeHigh: UInt8 = 0\n public var lastcheckHigh: UInt8 = 0\n public var firstErrorTimeHigh: UInt8 = 0\n public var lastErrorTimeHigh: UInt8 = 0\n public var pad: (UInt8, UInt8) = (0, 0)\n public var reserved:\n (\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n )\n public var checksum: UInt32 = 0\n }\n\n struct CompatFeature {\n let rawValue: UInt32\n\n static let dirPrealloc = CompatFeature(rawValue: 0x1)\n static let imagicInodes = CompatFeature(rawValue: 0x2)\n static let hasJournal = CompatFeature(rawValue: 0x4)\n static let extAttr = CompatFeature(rawValue: 0x8)\n static let resizeInode = CompatFeature(rawValue: 0x10)\n static let dirIndex = CompatFeature(rawValue: 0x20)\n static let lazyBg = CompatFeature(rawValue: 0x40)\n static let excludeInode = CompatFeature(rawValue: 0x80)\n static let excludeBitmap = CompatFeature(rawValue: 0x100)\n static let sparseSuper2 = CompatFeature(rawValue: 0x200)\n }\n\n struct IncompatFeature {\n let rawValue: UInt32\n\n static let compression = IncompatFeature(rawValue: 0x1)\n static let filetype = IncompatFeature(rawValue: 0x2)\n static let recover = IncompatFeature(rawValue: 0x4)\n static let journalDev = IncompatFeature(rawValue: 0x8)\n static let metaBg = IncompatFeature(rawValue: 0x10)\n static let extents = IncompatFeature(rawValue: 0x40)\n static let bit64 = IncompatFeature(rawValue: 0x80)\n static let mmp = IncompatFeature(rawValue: 0x100)\n static let flexBg = IncompatFeature(rawValue: 0x200)\n static let eaInode = IncompatFeature(rawValue: 0x400)\n static let dirdata = IncompatFeature(rawValue: 0x1000)\n static let csumSeed = IncompatFeature(rawValue: 0x2000)\n static let largedir = IncompatFeature(rawValue: 0x4000)\n static let inlineData = IncompatFeature(rawValue: 0x8000)\n static let encrypt = IncompatFeature(rawValue: 0x10000)\n }\n\n struct RoCompatFeature {\n let rawValue: UInt32\n\n static let sparseSuper = RoCompatFeature(rawValue: 0x1)\n static let largeFile = RoCompatFeature(rawValue: 0x2)\n static let btreeDir = RoCompatFeature(rawValue: 0x4)\n static let hugeFile = RoCompatFeature(rawValue: 0x8)\n static let gdtCsum = RoCompatFeature(rawValue: 0x10)\n static let dirNlink = RoCompatFeature(rawValue: 0x20)\n static let extraIsize = RoCompatFeature(rawValue: 0x40)\n static let hasSnapshot = RoCompatFeature(rawValue: 0x80)\n static let quota = RoCompatFeature(rawValue: 0x100)\n static let bigalloc = RoCompatFeature(rawValue: 0x200)\n static let metadataCsum = RoCompatFeature(rawValue: 0x400)\n static let replica = RoCompatFeature(rawValue: 0x800)\n static let readonly = RoCompatFeature(rawValue: 0x1000)\n static let project = RoCompatFeature(rawValue: 0x2000)\n }\n\n struct BlockGroupFlag {\n let rawValue: UInt16\n\n static let inodeUninit = BlockGroupFlag(rawValue: 0x1)\n static let blockUninit = BlockGroupFlag(rawValue: 0x2)\n static let inodeZeroed = BlockGroupFlag(rawValue: 0x4)\n }\n\n struct GroupDescriptor {\n let blockBitmapLow: UInt32\n let inodeBitmapLow: UInt32\n let inodeTableLow: UInt32\n let freeBlocksCountLow: UInt16\n let freeInodesCountLow: UInt16\n let usedDirsCountLow: UInt16\n let flags: UInt16\n let excludeBitmapLow: UInt32\n let blockBitmapCsumLow: UInt16\n let inodeBitmapCsumLow: UInt16\n let itableUnusedLow: UInt16\n let checksum: UInt16\n }\n\n struct GroupDescriptor64 {\n let groupDescriptor: GroupDescriptor\n let blockBitmapHigh: UInt32\n let inodeBitmapHigh: UInt32\n let inodeTableHigh: UInt32\n let freeBlocksCountHigh: UInt16\n let freeInodesCountHigh: UInt16\n let usedDirsCountHigh: UInt16\n let itableUnusedHigh: UInt16\n let excludeBitmapHigh: UInt32\n let blockBitmapCsumHigh: UInt16\n let inodeBitmapCsumHigh: UInt16\n let reserved: UInt32\n }\n\n public struct FileModeFlag: Sendable {\n let rawValue: UInt16\n\n public static let S_IXOTH = FileModeFlag(rawValue: 0x1)\n public static let S_IWOTH = FileModeFlag(rawValue: 0x2)\n public static let S_IROTH = FileModeFlag(rawValue: 0x4)\n public static let S_IXGRP = FileModeFlag(rawValue: 0x8)\n public static let S_IWGRP = FileModeFlag(rawValue: 0x10)\n public static let S_IRGRP = FileModeFlag(rawValue: 0x20)\n public static let S_IXUSR = FileModeFlag(rawValue: 0x40)\n public static let S_IWUSR = FileModeFlag(rawValue: 0x80)\n public static let S_IRUSR = FileModeFlag(rawValue: 0x100)\n public static let S_ISVTX = FileModeFlag(rawValue: 0x200)\n public static let S_ISGID = FileModeFlag(rawValue: 0x400)\n public static let S_ISUID = FileModeFlag(rawValue: 0x800)\n public static let S_IFIFO = FileModeFlag(rawValue: 0x1000)\n public static let S_IFCHR = FileModeFlag(rawValue: 0x2000)\n public static let S_IFDIR = FileModeFlag(rawValue: 0x4000)\n public static let S_IFBLK = FileModeFlag(rawValue: 0x6000)\n public static let S_IFREG = FileModeFlag(rawValue: 0x8000)\n public static let S_IFLNK = FileModeFlag(rawValue: 0xA000)\n public static let S_IFSOCK = FileModeFlag(rawValue: 0xC000)\n\n public static let TypeMask = FileModeFlag(rawValue: 0xF000)\n }\n\n typealias InodeNumber = UInt32\n\n public struct Inode {\n var mode: UInt16 = 0\n var uid: UInt16 = 0\n var sizeLow: UInt32 = 0\n var atime: UInt32 = 0\n var ctime: UInt32 = 0\n var mtime: UInt32 = 0\n var dtime: UInt32 = 0\n var gid: UInt16 = 0\n var linksCount: UInt16 = 0\n var blocksLow: UInt32 = 0\n var flags: UInt32 = 0\n var version: UInt32 = 0\n var block:\n (\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n )\n var generation: UInt32 = 0\n var xattrBlockLow: UInt32 = 0\n var sizeHigh: UInt32 = 0\n var obsoleteFragmentAddr: UInt32 = 0\n var blocksHigh: UInt16 = 0\n var xattrBlockHigh: UInt16 = 0\n var uidHigh: UInt16 = 0\n var gidHigh: UInt16 = 0\n var checksumLow: UInt16 = 0\n var reserved: UInt16 = 0\n var extraIsize: UInt16 = 0\n var checksumHigh: UInt16 = 0\n var ctimeExtra: UInt32 = 0\n var mtimeExtra: UInt32 = 0\n var atimeExtra: UInt32 = 0\n var crtime: UInt32 = 0\n var crtimeExtra: UInt32 = 0\n var versionHigh: UInt32 = 0\n var projid: UInt32 = 0 // Size until this point is 160 bytes\n var inlineXattrs:\n ( // 96 bytes for extended attributes\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,\n UInt8, UInt8, UInt8, UInt8, UInt8, UInt8\n ) = (\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0\n )\n\n public static func Mode(_ mode: FileModeFlag, _ perm: UInt16) -> UInt16 {\n mode.rawValue | perm\n }\n }\n\n struct InodeFlag {\n let rawValue: UInt32\n\n static let secRm = InodeFlag(rawValue: 0x1)\n static let unRm = InodeFlag(rawValue: 0x2)\n static let compressed = InodeFlag(rawValue: 0x4)\n static let sync = InodeFlag(rawValue: 0x8)\n static let immutable = InodeFlag(rawValue: 0x10)\n static let append = InodeFlag(rawValue: 0x20)\n static let noDump = InodeFlag(rawValue: 0x40)\n static let noAtime = InodeFlag(rawValue: 0x80)\n static let dirtyCompressed = InodeFlag(rawValue: 0x100)\n static let compressedClusters = InodeFlag(rawValue: 0x200)\n static let noCompress = InodeFlag(rawValue: 0x400)\n static let encrypted = InodeFlag(rawValue: 0x800)\n static let hashedIndex = InodeFlag(rawValue: 0x1000)\n static let magic = InodeFlag(rawValue: 0x2000)\n static let journalData = InodeFlag(rawValue: 0x4000)\n static let noTail = InodeFlag(rawValue: 0x8000)\n static let dirSync = InodeFlag(rawValue: 0x10000)\n static let topDir = InodeFlag(rawValue: 0x20000)\n static let hugeFile = InodeFlag(rawValue: 0x40000)\n static let extents = InodeFlag(rawValue: 0x80000)\n static let eaInode = InodeFlag(rawValue: 0x200000)\n static let eofBlocks = InodeFlag(rawValue: 0x400000)\n static let snapfile = InodeFlag(rawValue: 0x0100_0000)\n static let snapfileDeleted = InodeFlag(rawValue: 0x0400_0000)\n static let snapfileShrunk = InodeFlag(rawValue: 0x0800_0000)\n static let inlineData = InodeFlag(rawValue: 0x1000_0000)\n static let projectIDInherit = InodeFlag(rawValue: 0x2000_0000)\n static let reserved = InodeFlag(rawValue: 0x8000_0000)\n }\n\n struct ExtentHeader {\n let magic: UInt16\n let entries: UInt16\n let max: UInt16\n let depth: UInt16\n let generation: UInt32\n }\n\n struct ExtentIndex {\n let block: UInt32\n let leafLow: UInt32\n let leafHigh: UInt16\n let unused: UInt16\n }\n\n struct ExtentLeaf {\n let block: UInt32\n let length: UInt16\n let startHigh: UInt16\n let startLow: UInt32\n }\n\n struct ExtentTail {\n let checksum: UInt32\n }\n\n struct ExtentIndexNode {\n var header: ExtentHeader\n var indices: [ExtentIndex]\n }\n\n struct ExtentLeafNode {\n var header: ExtentHeader\n var leaves: [ExtentLeaf]\n }\n\n struct DirectoryEntry {\n let inode: InodeNumber\n let recordLength: UInt16\n let nameLength: UInt8\n let fileType: UInt8\n // let name: [UInt8]\n }\n\n enum FileType: UInt8 {\n case unknown = 0x0\n case regular = 0x1\n case directory = 0x2\n case character = 0x3\n case block = 0x4\n case fifo = 0x5\n case socket = 0x6\n case symbolicLink = 0x7\n }\n\n struct DirectoryEntryTail {\n let reservedZero1: UInt32\n let recordLength: UInt16\n let reservedZero2: UInt8\n let fileType: UInt8\n let checksum: UInt32\n }\n\n struct DirectoryTreeRoot {\n let dot: DirectoryEntry\n let dotName: [UInt8]\n let dotDot: DirectoryEntry\n let dotDotName: [UInt8]\n let reservedZero: UInt32\n let hashVersion: UInt8\n let infoLength: UInt8\n let indirectLevels: UInt8\n let unusedFlags: UInt8\n let limit: UInt16\n let count: UInt16\n let block: UInt32\n // let entries: [DirectoryTreeEntry]\n }\n\n struct DirectoryTreeNode {\n let fakeInode: UInt32\n let fakeRecordLength: UInt16\n let nameLength: UInt8\n let fileType: UInt8\n let limit: UInt16\n let count: UInt16\n let block: UInt32\n // let entries: [DirectoryTreeEntry]\n }\n\n struct DirectoryTreeEntry {\n let hash: UInt32\n let block: UInt32\n }\n\n struct DirectoryTreeTail {\n let reserved: UInt32\n let checksum: UInt32\n }\n\n struct XAttrEntry {\n let nameLength: UInt8\n let nameIndex: UInt8\n let valueOffset: UInt16\n let valueInum: UInt32\n let valueSize: UInt32\n let hash: UInt32\n }\n\n struct XAttrHeader {\n let magic: UInt32\n let referenceCount: UInt32\n let blocks: UInt32\n let hash: UInt32\n let checksum: UInt32\n let reserved: [UInt32]\n }\n\n}\n\nextension EXT4.Inode {\n public static func Root() -> EXT4.Inode {\n var inode = Self() // inode\n inode.mode = Self.Mode(.S_IFDIR, 0o755)\n inode.linksCount = 2\n inode.uid = 0\n inode.gid = 0\n // time\n let now = Date().fs()\n let now_lo: UInt32 = now.lo\n let now_hi: UInt32 = now.hi\n inode.atime = now_lo\n inode.atimeExtra = now_hi\n inode.ctime = now_lo\n inode.ctimeExtra = now_hi\n inode.mtime = now_lo\n inode.mtimeExtra = now_hi\n inode.crtime = now_lo\n inode.crtimeExtra = now_hi\n inode.flags = EXT4.InodeFlag.hugeFile.rawValue\n inode.extraIsize = UInt16(EXT4.ExtraIsize)\n return inode\n }\n}\n"], ["/containerization/Sources/Containerization/UnixSocketConfiguration.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\n/// Represents a UnixSocket that can be shared into or out of a container/guest.\npublic struct UnixSocketConfiguration: Sendable {\n // TODO: Realistically, we can just hash this struct and use it as the \"id\".\n package var id: String {\n _id\n }\n\n private let _id = UUID().uuidString\n\n /// The path to the socket you'd like relayed. For .into\n /// direction this should be the path on the host to a unix socket.\n /// For direction .outOf this should be the path in the container/guest\n /// to a unix socket.\n public var source: URL\n\n /// The path you'd like the socket to be relayed to. For .into\n /// direction this should be the path in the container/guest. For\n /// direction .outOf this should be the path on your host.\n public var destination: URL\n\n /// What to set the file permissions of the unix socket being created\n /// to. For .into direction this will be the socket in the guest. For\n /// .outOf direction this will be the socket on the host.\n public var permissions: FilePermissions?\n\n /// The direction of the relay. `.into` for sharing a unix socket on your\n /// host into the container/guest. `outOf` shares a socket in the container/guest\n /// onto your host.\n public var direction: Direction\n\n /// Type that denotes the direction of the unix socket relay.\n public enum Direction: Sendable {\n /// Share the socket into the container/guest.\n case into\n /// Share a socket in the container/guest onto the host.\n case outOf\n }\n\n public init(\n source: URL,\n destination: URL,\n permissions: FilePermissions? = nil,\n direction: Direction = .into\n ) {\n self.source = source\n self.destination = destination\n self.permissions = permissions\n self.direction = direction\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/UnsafeLittleEndianBytes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n// takes a pointer and converts its contents to native endian bytes\npublic func withUnsafeLittleEndianBytes(of value: T, body: (UnsafeRawBufferPointer) throws -> Result)\n rethrows -> Result\n{\n switch Endian {\n case .little:\n return try withUnsafeBytes(of: value) { bytes in\n try body(bytes)\n }\n case .big:\n return try withUnsafeBytes(of: value) { buffer in\n let reversedBuffer = Array(buffer.reversed())\n return try reversedBuffer.withUnsafeBytes { buf in\n try body(buf)\n }\n }\n }\n}\n\npublic func withUnsafeLittleEndianBuffer(\n of value: UnsafeRawBufferPointer, body: (UnsafeRawBufferPointer) throws -> T\n) rethrows -> T {\n switch Endian {\n case .little:\n return try body(value)\n case .big:\n let reversed = Array(value.reversed())\n return try reversed.withUnsafeBytes { buf in\n try body(buf)\n }\n }\n}\n\nextension UnsafeRawBufferPointer {\n // loads littleEndian raw data, converts it native endian format and calls UnsafeRawBufferPointer.load\n public func loadLittleEndian(as type: T.Type) -> T {\n switch Endian {\n case .little:\n return self.load(as: T.self)\n case .big:\n let buffer = Array(self.reversed())\n return buffer.withUnsafeBytes { ptr in\n ptr.load(as: T.self)\n }\n }\n }\n}\n\npublic enum Endianness {\n case little\n case big\n}\n\n// returns current endianness\npublic var Endian: Endianness {\n switch CFByteOrderGetCurrent() {\n case CFByteOrder(CFByteOrderLittleEndian.rawValue):\n return .little\n case CFByteOrder(CFByteOrderBigEndian.rawValue):\n return .big\n default:\n fatalError(\"impossible\")\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/Integer+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension UInt64 {\n public var lo: UInt32 {\n UInt32(self & 0xffff_ffff)\n }\n\n public var hi: UInt32 {\n UInt32(self >> 32)\n }\n\n public static func - (lhs: Self, rhs: UInt32) -> UInt64 {\n lhs - UInt64(rhs)\n }\n\n public static func % (lhs: Self, rhs: UInt32) -> UInt64 {\n lhs % UInt64(rhs)\n }\n\n public static func / (lhs: Self, rhs: UInt32) -> UInt32 {\n (lhs / UInt64(rhs)).lo\n }\n\n public static func * (lhs: Self, rhs: UInt32) -> UInt64 {\n lhs * UInt64(rhs)\n }\n\n public static func * (lhs: Self, rhs: Int) -> UInt64 {\n lhs * UInt64(rhs)\n }\n}\n\nextension UInt32 {\n public var lo: UInt16 {\n UInt16(self & 0xffff)\n }\n\n public var hi: UInt16 {\n UInt16(self >> 16)\n }\n\n public static func + (lhs: Self, rhs: Int.IntegerLiteralType) -> UInt32 {\n lhs + UInt32(rhs)\n }\n\n public static func - (lhs: Self, rhs: Int.IntegerLiteralType) -> UInt32 {\n lhs - UInt32(rhs)\n }\n\n public static func / (lhs: Self, rhs: Int.IntegerLiteralType) -> UInt32 {\n lhs / UInt32(rhs)\n }\n\n public static func - (lhs: Self, rhs: UInt16) -> UInt32 {\n lhs - UInt32(rhs)\n }\n\n public static func * (lhs: Self, rhs: Int.IntegerLiteralType) -> Int {\n Int(lhs) * rhs\n }\n}\n\nextension Int {\n public static func + (lhs: Self, rhs: UInt32) -> Int {\n lhs + Int(rhs)\n }\n\n public static func + (lhs: Self, rhs: UInt32) -> UInt32 {\n UInt32(lhs) + rhs\n }\n}\n\nextension UInt16 {\n func isDir() -> Bool {\n self & EXT4.FileModeFlag.TypeMask.rawValue == EXT4.FileModeFlag.S_IFDIR.rawValue\n }\n\n func isLink() -> Bool {\n self & EXT4.FileModeFlag.TypeMask.rawValue == EXT4.FileModeFlag.S_IFLNK.rawValue\n }\n\n func isReg() -> Bool {\n self & EXT4.FileModeFlag.TypeMask.rawValue == EXT4.FileModeFlag.S_IFREG.rawValue\n }\n\n func fileType() -> UInt8 {\n typealias FMode = EXT4.FileModeFlag\n typealias FileType = EXT4.FileType\n switch self & FMode.TypeMask.rawValue {\n case FMode.S_IFREG.rawValue:\n return FileType.regular.rawValue\n case FMode.S_IFDIR.rawValue:\n return FileType.directory.rawValue\n case FMode.S_IFCHR.rawValue:\n return FileType.character.rawValue\n case FMode.S_IFBLK.rawValue:\n return FileType.block.rawValue\n case FMode.S_IFIFO.rawValue:\n return FileType.fifo.rawValue\n case FMode.S_IFSOCK.rawValue:\n return FileType.socket.rawValue\n case FMode.S_IFLNK.rawValue:\n return FileType.symbolicLink.rawValue\n default:\n return FileType.unknown.rawValue\n }\n }\n}\n\nextension [UInt8] {\n var allZeros: Bool {\n for num in self where num != 0 {\n return false\n }\n return true\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Descriptor.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// Source: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/descriptor.go\n\nimport Foundation\n\n/// Descriptor describes the disposition of targeted content.\n/// This structure provides `application/vnd.oci.descriptor.v1+json` mediatype\n/// when marshalled to JSON.\npublic struct Descriptor: Codable, Sendable, Equatable {\n /// mediaType is the media type of the object this schema refers to.\n public let mediaType: String\n\n /// digest is the digest of the targeted content.\n public let digest: String\n\n /// size specifies the size in bytes of the blob.\n public let size: Int64\n\n /// urls specifies a list of URLs from which this object MAY be downloaded.\n public let urls: [String]?\n\n /// annotations contains arbitrary metadata relating to the targeted content.\n public var annotations: [String: String]?\n\n /// platform describes the platform which the image in the manifest runs on.\n ///\n /// This should only be used when referring to a manifest.\n public var platform: Platform?\n\n public init(\n mediaType: String, digest: String, size: Int64, urls: [String]? = nil, annotations: [String: String]? = nil,\n platform: Platform? = nil\n ) {\n self.mediaType = mediaType\n self.digest = digest\n self.size = size\n self.urls = urls\n self.annotations = annotations\n self.platform = platform\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/AsyncTypes.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npackage actor AsyncStore {\n private var _value: T?\n\n package init(_ value: T? = nil) {\n self._value = value\n }\n\n package func get() -> T? {\n self._value\n }\n\n package func set(_ value: T) {\n self._value = value\n }\n}\n\npackage actor AsyncSet {\n private var buffer: Set\n\n package init(_ elements: S) where S.Element == T {\n buffer = Set(elements)\n }\n\n package var count: Int {\n buffer.count\n }\n\n package func insert(_ element: T) {\n buffer.insert(element)\n }\n\n @discardableResult\n package func remove(_ element: T) -> T? {\n buffer.remove(element)\n }\n\n package func contains(_ element: T) -> Bool {\n buffer.contains(element)\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Client/Authentication.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Abstraction for returning a token needed for logging into an OCI compliant registry.\npublic protocol Authentication: Sendable {\n func token() async throws -> String\n}\n\n/// Type representing authentication information for client to access the registry.\npublic struct BasicAuthentication: Authentication {\n /// The username for the authentication.\n let username: String\n /// The password or identity token for the user.\n let password: String\n\n public init(username: String, password: String) {\n self.username = username\n self.password = password\n }\n\n /// Get a token using the provided username and password. This will be a\n /// base64 encoded string of the username and password delimited by a colon.\n public func token() async throws -> String {\n let credentials = \"\\(username):\\(password)\"\n if let authenticationData = credentials.data(using: .utf8)?.base64EncodedString() {\n return \"Basic \\(authenticationData)\"\n }\n throw Error.invalidCredentials\n }\n\n /// `BasicAuthentication` errors.\n public enum Error: Swift.Error {\n case invalidCredentials\n }\n}\n"], ["/containerization/Sources/ContainerizationArchive/FileArchiveWriterDelegate.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport SystemPackage\n\ninternal final class FileArchiveWriterDelegate {\n public let path: FilePath\n private var fd: FileDescriptor!\n\n public init(path: FilePath) {\n self.path = path\n }\n\n public convenience init(url: URL) {\n self.init(path: FilePath(url.path))\n }\n\n public func open(archive: ArchiveWriter) throws {\n self.fd = try FileDescriptor.open(\n self.path, .writeOnly, options: [.create, .append], permissions: [.groupRead, .otherRead, .ownerReadWrite])\n }\n\n public func write(archive: ArchiveWriter, buffer: UnsafeRawBufferPointer) throws -> Int {\n try fd.write(buffer)\n }\n\n public func close(archive: ArchiveWriter) throws {\n try self.fd.close()\n }\n\n public func free(archive: ArchiveWriter) {\n self.fd = nil\n }\n\n deinit {\n if let fd = self.fd {\n try? fd.close()\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/Timeout.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// `Timeout` contains helpers to run an operation and error out if\n/// the operation does not finish within a provided time.\npublic struct Timeout {\n /// Performs the passed in `operation` and throws a `CancellationError` if the operation\n /// doesn't finish in the provided `seconds` amount.\n public static func run(\n seconds: UInt32,\n operation: @escaping @Sendable () async -> T\n ) async throws -> T {\n try await withThrowingTaskGroup(of: T.self) { group in\n group.addTask {\n await operation()\n }\n\n group.addTask {\n try await Task.sleep(for: .seconds(seconds))\n throw CancellationError()\n }\n\n guard let result = try await group.next() else {\n fatalError()\n }\n\n group.cancelAll()\n return result\n }\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/OSFile+Splice.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension OSFile {\n struct SpliceFile: Sendable {\n var file: OSFile\n var offset: Int\n let pipe = Pipe()\n\n var fileDescriptor: Int32 {\n file.fileDescriptor\n }\n\n var reader: Int32 {\n pipe.fileHandleForReading.fileDescriptor\n }\n\n var writer: Int32 {\n pipe.fileHandleForWriting.fileDescriptor\n }\n\n init(fd: Int32) {\n self.file = OSFile(fd: fd)\n self.offset = 0\n }\n\n init(handle: FileHandle) {\n self.file = OSFile(handle: handle)\n self.offset = 0\n }\n\n init(from: OSFile, withOffset: Int = 0) {\n self.file = from\n self.offset = withOffset\n }\n\n func close() throws {\n try self.file.close()\n }\n }\n\n static func splice(from: inout SpliceFile, to: inout SpliceFile, count: Int = 1 << 16) throws -> (read: Int, wrote: Int, action: IOAction) {\n let fromOffset = from.offset\n let toOffset = to.offset\n\n while true {\n while (from.offset - to.offset) < count {\n let toRead = count - (from.offset - to.offset)\n let bytesRead = Foundation.splice(from.fileDescriptor, nil, to.writer, nil, toRead, UInt32(bitPattern: SPLICE_F_MOVE | SPLICE_F_NONBLOCK))\n if bytesRead == -1 {\n if errno != EAGAIN && errno != EIO {\n throw POSIXError(.init(rawValue: errno)!)\n }\n break\n }\n if bytesRead == 0 {\n return (0, 0, .eof)\n }\n from.offset += bytesRead\n if bytesRead < toRead {\n break\n }\n }\n if from.offset == to.offset {\n return (from.offset - fromOffset, to.offset - toOffset, .success)\n }\n while to.offset < from.offset {\n let toWrite = from.offset - to.offset\n let bytesWrote = Foundation.splice(to.reader, nil, to.fileDescriptor, nil, toWrite, UInt32(bitPattern: SPLICE_F_MOVE | SPLICE_F_NONBLOCK))\n if bytesWrote == -1 {\n if errno != EAGAIN && errno != EIO {\n throw POSIXError(.init(rawValue: errno)!)\n }\n break\n }\n to.offset += bytesWrote\n if bytesWrote == 0 {\n return (from.offset - fromOffset, to.offset - toOffset, .brokenPipe)\n }\n if bytesWrote < toWrite {\n break\n }\n }\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/Content.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport Crypto\nimport Foundation\nimport NIOCore\n\n/// Protocol for defining a single OCI content\npublic protocol Content: Sendable {\n /// URL to the content\n var path: URL { get }\n\n /// sha256 of content\n func digest() throws -> SHA256.Digest\n\n /// Size of content\n func size() throws -> UInt64\n\n /// Data representation of entire content\n func data() throws -> Data\n\n /// Data representation partial content\n func data(offset: UInt64, length: Int) throws -> Data?\n\n /// Decode the content into an object\n func decode() throws -> T where T: Decodable\n}\n\n/// Protocol defining methods to fetch and push OCI content\npublic protocol ContentClient: Sendable {\n func fetch(name: String, descriptor: Descriptor) async throws -> T\n\n func fetchBlob(name: String, descriptor: Descriptor, into file: URL, progress: ProgressHandler?) async throws -> (Int64, SHA256Digest)\n\n func fetchData(name: String, descriptor: Descriptor) async throws -> Data\n\n func push(\n name: String,\n ref: String,\n descriptor: Descriptor,\n streamGenerator: () throws -> T,\n progress: ProgressHandler?\n ) async throws where T.Element == ByteBuffer\n\n}\n"], ["/containerization/Sources/Containerization/SystemPlatform.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOCI\n\n/// `SystemPlatform` describes an operating system and architecture pair.\n/// This is primarily used to choose what kind of OCI image to pull from a\n/// registry.\npublic struct SystemPlatform: Sendable, Codable {\n public enum OS: String, CaseIterable, Sendable, Codable {\n case linux\n case darwin\n }\n public let os: OS\n\n public enum Architecture: String, CaseIterable, Sendable, Codable {\n case arm64\n case amd64\n }\n public let architecture: Architecture\n\n public func ociPlatform() -> ContainerizationOCI.Platform {\n ContainerizationOCI.Platform(arch: architecture.rawValue, os: os.rawValue)\n }\n\n public static var linuxArm: SystemPlatform { .init(os: .linux, architecture: .arm64) }\n public static var linuxAmd: SystemPlatform { .init(os: .linux, architecture: .amd64) }\n}\n"], ["/containerization/Sources/Containerization/IO/Terminal+ReaderStream.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\n\nextension Terminal: ReaderStream {\n public func stream() -> AsyncStream {\n .init { cont in\n self.handle.readabilityHandler = { handle in\n let data = handle.availableData\n if data.isEmpty {\n self.handle.readabilityHandler = nil\n cont.finish()\n return\n }\n cont.yield(data)\n }\n }\n }\n}\n\nextension Terminal: Writer {}\n"], ["/containerization/Sources/ContainerizationOS/Pipe+Close.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension Pipe {\n /// Close both sides of the pipe.\n public func close() throws {\n var err: Swift.Error?\n do {\n try self.fileHandleForReading.close()\n } catch {\n err = error\n }\n try self.fileHandleForWriting.close()\n if let err {\n throw err\n }\n }\n\n /// Ensure that both sides of the pipe are set with O_CLOEXEC.\n public func setCloexec() throws {\n if fcntl(self.fileHandleForWriting.fileDescriptor, F_SETFD, FD_CLOEXEC) == -1 {\n throw POSIXError(.init(rawValue: errno)!)\n }\n if fcntl(self.fileHandleForReading.fileDescriptor, F_SETFD, FD_CLOEXEC) == -1 {\n throw POSIXError(.init(rawValue: errno)!)\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Reaper.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A process reaper that returns exited processes along\n/// with their exit status.\npublic struct Reaper {\n /// Process's pid and exit status.\n typealias Exit = (pid: Int32, status: Int32)\n\n /// Reap all pending processes and return the pid and exit status.\n public static func reap() -> [Int32: Int32] {\n var reaped = [Int32: Int32]()\n while true {\n guard let exit = wait() else {\n return reaped\n }\n reaped[exit.pid] = exit.status\n }\n return reaped\n }\n\n /// Returns the exit status of the last process that exited.\n /// nil is returned when no pending processes exist.\n private static func wait() -> Exit? {\n var rus = rusage()\n var ws = Int32()\n\n let pid = wait4(-1, &ws, WNOHANG, &rus)\n if pid <= 0 {\n return nil\n }\n return (pid: pid, status: Command.toExitStatus(ws))\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Index.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// Source: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/index.go\n\nimport Foundation\n\n/// Index references manifests for various platforms.\n/// This structure provides `application/vnd.oci.image.index.v1+json` mediatype when marshalled to JSON.\npublic struct Index: Codable, Sendable {\n /// schemaVersion is the image manifest schema that this image follows\n public let schemaVersion: Int\n\n /// mediaType specifies the type of this document data structure e.g. `application/vnd.oci.image.index.v1+json`\n public let mediaType: String\n\n /// manifests references platform specific manifests.\n public var manifests: [Descriptor]\n\n /// annotations contains arbitrary metadata for the image index.\n public var annotations: [String: String]?\n\n public init(\n schemaVersion: Int = 2, mediaType: String = MediaTypes.index, manifests: [Descriptor],\n annotations: [String: String]? = nil\n ) {\n self.schemaVersion = schemaVersion\n self.mediaType = mediaType\n self.manifests = manifests\n self.annotations = annotations\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/FileManager+Size.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension FileManager {\n func fileSize(atPath path: String) -> Int64? {\n do {\n let attributes = try attributesOfItem(atPath: path)\n guard let fileSize = attributes[.size] as? NSNumber else {\n return nil\n }\n return fileSize.int64Value\n } catch {\n return nil\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/String+Extension.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension String {\n /// Removes any prefix (sha256:) from a digest string.\n public var trimmingDigestPrefix: String {\n let split = self.split(separator: \":\")\n if split.count == 2 {\n return String(split[1])\n }\n return self\n }\n}\n"], ["/containerization/Sources/ContainerizationEXT4/EXT4+Ptr.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension EXT4 {\n class Ptr {\n let underlying: UnsafeMutablePointer\n private var capacity: Int\n private var initialized: Bool\n private var allocated: Bool\n\n var pointee: T {\n underlying.pointee\n }\n\n init(capacity: Int) {\n self.underlying = UnsafeMutablePointer.allocate(capacity: capacity)\n self.capacity = capacity\n self.allocated = true\n self.initialized = false\n }\n\n static func allocate(capacity: Int) -> Ptr {\n Ptr(capacity: capacity)\n }\n\n func initialize(to value: T) {\n guard self.allocated else {\n return\n }\n if self.initialized {\n self.underlying.deinitialize(count: self.capacity)\n }\n self.underlying.initialize(to: value)\n self.allocated = true\n self.initialized = true\n }\n\n func deallocate() {\n guard self.allocated else {\n return\n }\n self.underlying.deallocate()\n self.allocated = false\n self.initialized = false\n }\n\n func deinitialize(count: Int) {\n guard self.allocated else {\n return\n }\n guard self.initialized else {\n return\n }\n self.underlying.deinitialize(count: count)\n self.initialized = false\n self.allocated = true\n }\n\n func move() -> T {\n self.initialized = false\n self.allocated = true\n return self.underlying.move()\n }\n\n deinit {\n self.deinitialize(count: self.capacity)\n self.deallocate()\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/BinaryInteger+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nextension BinaryInteger {\n private func toUnsignedMemoryAmount(_ amount: UInt64) -> UInt64 {\n guard self > 0 else {\n fatalError(\"encountered negative number during conversion to memory amount\")\n }\n let val = UInt64(self)\n let (newVal, overflow) = val.multipliedReportingOverflow(by: amount)\n guard !overflow else {\n fatalError(\"UInt64 overflow when converting to memory amount\")\n }\n return newVal\n }\n\n public func kib() -> UInt64 {\n self.toUnsignedMemoryAmount(1 << 10)\n }\n\n public func mib() -> UInt64 {\n self.toUnsignedMemoryAmount(1 << 20)\n }\n\n public func gib() -> UInt64 {\n self.toUnsignedMemoryAmount(1 << 30)\n }\n\n public func tib() -> UInt64 {\n self.toUnsignedMemoryAmount(1 << 40)\n }\n\n public func pib() -> UInt64 {\n self.toUnsignedMemoryAmount(1 << 50)\n }\n}\n"], ["/containerization/Sources/Containerization/Container.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// The core protocol container implementations must implement.\npublic protocol Container {\n /// ID for the container.\n var id: String { get }\n /// The amount of cpus assigned to the container.\n var cpus: Int { get }\n /// The memory in bytes assigned to the container.\n var memoryInBytes: UInt64 { get }\n /// The network interfaces assigned to the container.\n var interfaces: [any Interface] { get }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/SHA256+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Crypto\nimport Foundation\n\nextension SHA256.Digest {\n /// Returns the digest as a string.\n public var digestString: String {\n let parts = self.description.split(separator: \": \")\n return \"sha256:\\(parts[1])\"\n }\n\n /// Returns the digest without a 'sha256:' prefix.\n public var encoded: String {\n let parts = self.description.split(separator: \": \")\n return String(parts[1])\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Content/ContentStoreProtocol.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Crypto\nimport Foundation\n\n/// Protocol for defining a content store where OCI image metadata and layers will be managed\n/// and manipulated.\npublic protocol ContentStore: Sendable {\n /// Retrieves a piece of Content based on the digest string.\n /// Returns `nil` if the requested digest is not found.\n func get(digest: String) async throws -> Content?\n\n /// Retrieves a specific content metadata type based on the digest string.\n /// Returns `nil` if the requested digest is not found.\n func get(digest: String) async throws -> T?\n\n /// Remove a list of digests in the content store.\n @discardableResult\n func delete(digests: [String]) async throws -> ([String], UInt64)\n\n /// Removes all content from the store except for the digests in the provided list.\n @discardableResult\n func delete(keeping: [String]) async throws -> ([String], UInt64)\n\n /// Creates a transactional write to the content store.\n /// The function takes a closure given a temporary `URL` of the base directory which all contents should be written to.\n /// This is transaction write where any failed operation in the closure (caught exception) will result in all contents written\n /// in the closure to be deleted.\n ///\n /// If the closure succeeds, then all the content that have been written to the temporary `URL` will be moved into the actual\n /// blobs path of the content store.\n @discardableResult\n func ingest(_ body: @Sendable @escaping (URL) async throws -> Void) async throws -> [String]\n\n /// Creates a new ingest session and returns the session ID and temporary ingest directory corresponding to the session.\n /// The contents from the ingest directory are processed and moved into the content store once the session is marked complete.\n /// This can be done by invoking the `completeIngestSession` method with the returned session ID.\n func newIngestSession() async throws -> (id: String, ingestDir: URL)\n\n /// Completes a previously started ingest session corresponding to `id`.\n /// The contents from the ingest directory from the session are moved into the content store atomically.\n /// Any failure encountered will result in a transaction failure causing none of the contents to be ingested into the store.\n @discardableResult\n func completeIngestSession(_ id: String) async throws -> [String]\n\n /// Cancels a previously started ingest session corresponding to `id`.\n /// The contents from the ingest directory corresponding to the session are removed.\n func cancelIngestSession(_ id: String) async throws\n}\n"], ["/containerization/Sources/ContainerizationExtras/ProgressEvent.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A progress update event.\npublic struct ProgressEvent: Sendable {\n /// The event name. The possible values:\n /// - `add-items`: Increment the number of processed items by `value`.\n /// - `add-total-items`: Increment the total number of items to process by `value`.\n /// - `add-size`: Increment the size of processed items by `value`.\n /// - `add-total-size`: Increment the total size of items to process by `value`.\n public let event: String\n /// The event value.\n public let value: any Sendable\n\n /// Creates an instance.\n /// - Parameters:\n /// - event: The event name.\n /// - value: The event value.\n public init(event: String, value: any Sendable) {\n self.event = event\n self.value = value\n }\n}\n\n/// The progress update handler.\npublic typealias ProgressHandler = @Sendable (_ events: [ProgressEvent]) async -> Void\n"], ["/containerization/Sources/ContainerizationOS/Socket/SocketType.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if canImport(Musl)\nimport Musl\n#elseif canImport(Glibc)\nimport Glibc\n#elseif canImport(Darwin)\nimport Darwin\n#else\n#error(\"SocketType not supported on this platform.\")\n#endif\n\n/// Protocol used to describe the family of socket to be created with `Socket`.\npublic protocol SocketType: Sendable, CustomStringConvertible {\n /// The domain for the socket (AF_UNIX, AF_VSOCK etc.)\n var domain: Int32 { get }\n /// The type of socket (SOCK_STREAM).\n var type: Int32 { get }\n\n /// Actions to perform before calling bind(2).\n func beforeBind(fd: Int32) throws\n /// Actions to perform before calling listen(2).\n func beforeListen(fd: Int32) throws\n\n /// Handle accept(2) for an implementation of a socket type.\n func accept(fd: Int32) throws -> (Int32, SocketType)\n /// Provide a sockaddr pointer (by casting a socket specific type like sockaddr_un for example).\n func withSockAddr(_ closure: (_ ptr: UnsafePointer, _ len: UInt32) throws -> Void) throws\n}\n\nextension SocketType {\n public func beforeBind(fd: Int32) {}\n public func beforeListen(fd: Int32) {}\n}\n"], ["/containerization/Sources/ContainerizationArchive/TempDir.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport Foundation\n\ninternal func createTemporaryDirectory(baseName: String) -> URL? {\n let url = FileManager.default.uniqueTemporaryDirectory().appendingPathComponent(\n \"\\(baseName).XXXXXX\")\n guard let templatePathData = (url.absoluteURL.path as NSString).utf8String else {\n return nil\n }\n\n let pathData = UnsafeMutablePointer(mutating: templatePathData)\n mkdtemp(pathData)\n\n return URL(fileURLWithPath: String(cString: pathData), isDirectory: true)\n}\n"], ["/containerization/Sources/ContainerizationEXT4/FileTimestamps.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct FileTimestamps {\n public var access: Date\n public var modification: Date\n public var creation: Date\n public var now: Date\n\n public var accessLo: UInt32 {\n access.fs().lo\n }\n\n public var accessHi: UInt32 {\n access.fs().hi\n }\n\n public var modificationLo: UInt32 {\n modification.fs().lo\n }\n\n public var modificationHi: UInt32 {\n modification.fs().hi\n }\n\n public var creationLo: UInt32 {\n creation.fs().lo\n }\n\n public var creationHi: UInt32 {\n creation.fs().hi\n }\n\n public var nowLo: UInt32 {\n now.fs().lo\n }\n\n public var nowHi: UInt32 {\n now.fs().hi\n }\n\n public init(access: Date?, modification: Date?, creation: Date?) {\n now = Date()\n self.access = access ?? now\n self.modification = modification ?? now\n self.creation = creation ?? now\n }\n\n public init() {\n self.init(access: nil, modification: nil, creation: nil)\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/Syscall.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n#if canImport(Musl)\nimport Musl\n#elseif canImport(Glibc)\nimport Glibc\n#elseif canImport(Darwin)\nimport Darwin\n#else\n#error(\"retryingSyscall not supported on this platform.\")\n#endif\n\n/// Helper type to deal with running system calls.\npublic struct Syscall {\n /// Retry a syscall on EINTR.\n public static func retrying(_ closure: () -> T) -> T {\n while true {\n let res = closure()\n if res == -1 && errno == EINTR {\n continue\n }\n return res\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/Version.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\npublic struct RuntimeSpecVersion: Sendable {\n public let major, minor, patch: Int\n public let dev: String\n\n public static let current = RuntimeSpecVersion(\n major: 1,\n minor: 0,\n patch: 2,\n dev: \"-dev\"\n )\n\n public init(major: Int, minor: Int, patch: Int, dev: String) {\n self.major = major\n self.minor = minor\n self.patch = patch\n self.dev = dev\n }\n}\n"], ["/containerization/Sources/ContainerizationExtras/FileManager+Temporary.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension FileManager {\n /// Returns a unique temporary directory to use.\n public func uniqueTemporaryDirectory(create: Bool = true) -> URL {\n let tempDirectoryURL = temporaryDirectory\n let uniqueDirectoryURL = tempDirectoryURL.appendingPathComponent(UUID().uuidString)\n if create {\n try? createDirectory(at: uniqueDirectoryURL, withIntermediateDirectories: true, attributes: nil)\n }\n return uniqueDirectoryURL\n }\n}\n"], ["/containerization/Sources/ContainerizationOCI/MediaType.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// MediaTypes represent all supported OCI image content types for both metadata and layer formats.\n/// Follows all distributable media types in: https://github.com/opencontainers/image-spec/blob/main/specs-go/v1/mediatype.go\npublic struct MediaTypes: Codable, Sendable {\n /// Specifies the media type for a content descriptor.\n public static let descriptor = \"application/vnd.oci.descriptor.v1+json\"\n\n /// Specifies the media type for the oci-layout.\n public static let layoutHeader = \"application/vnd.oci.layout.header.v1+json\"\n\n /// Specifies the media type for an image index.\n public static let index = \"application/vnd.oci.image.index.v1+json\"\n\n /// Specifies the media type for an image manifest.\n public static let imageManifest = \"application/vnd.oci.image.manifest.v1+json\"\n\n /// Specifies the media type for the image configuration.\n public static let imageConfig = \"application/vnd.oci.image.config.v1+json\"\n\n /// Specifies the media type for an unused blob containing the value \"{}\".\n public static let emptyJSON = \"application/vnd.oci.empty.v1+json\"\n\n /// Specifies the media type for a Docker image manifest.\n public static let dockerManifest = \"application/vnd.docker.distribution.manifest.v2+json\"\n\n /// Specifies the media type for a Docker image manifest list.\n public static let dockerManifestList = \"application/vnd.docker.distribution.manifest.list.v2+json\"\n\n /// The Docker media type used for image configurations.\n public static let dockerImageConfig = \"application/vnd.docker.container.image.v1+json\"\n\n /// The media type used for layers referenced by the manifest.\n public static let imageLayer = \"application/vnd.oci.image.layer.v1.tar\"\n\n /// The media type used for gzipped layers referenced by the manifest.\n public static let imageLayerGzip = \"application/vnd.oci.image.layer.v1.tar+gzip\"\n\n /// The media type used for zstd compressed layers referenced by the manifest.\n public static let imageLayerZstd = \"application/vnd.oci.image.layer.v1.tar+zstd\"\n\n /// The Docker media type used for uncompressed layers referenced by an image manifest.\n public static let dockerImageLayer = \"application/vnd.docker.image.rootfs.diff.tar\"\n\n /// The Docker media type used for gzipped layers referenced by an image manifest.\n public static let dockerImageLayerGzip = \"application/vnd.docker.image.rootfs.diff.tar.gzip\"\n\n /// The Docker media type used for zstd compressed layers referenced by an image manifest.\n public static let dockerImageLayerZstd = \"application/vnd.docker.image.rootfs.diff.tar.zstd\"\n\n /// The media type used for in-toto attestations blobs.\n public static let inTotoAttestationBlob = \"application/vnd.in-toto+json\"\n}\n"], ["/containerization/Sources/SendablePropertyMacros/SendablePropertyError.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Errors that can be thrown by `@SendableProperty`.\nenum SendablePropertyError: CustomStringConvertible, Error {\n case unexpectedError\n case onlyApplicableToVar\n case notApplicableToType\n\n var description: String {\n switch self {\n case .unexpectedError: return \"The macro encountered an unexpected error\"\n case .onlyApplicableToVar: return \"The macro can only be applied to a variable\"\n case .notApplicableToType: return \"The macro can't be applied to a variable of this type\"\n }\n }\n}\n"], ["/containerization/Sources/ContainerizationOS/POSIXError+Helpers.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension POSIXError {\n public static func fromErrno() -> POSIXError {\n guard let errCode = POSIXErrorCode(rawValue: errno) else {\n fatalError(\"failed to convert errno to POSIXErrorCode\")\n }\n return POSIXError(errCode)\n }\n}\n"], ["/containerization/vminitd/Sources/vminitd/IOCloser+Extensions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationOS\nimport Foundation\n\nextension Socket: IOCloser {}\n\nextension Terminal: IOCloser {\n var fileDescriptor: Int32 {\n self.handle.fileDescriptor\n }\n}\n\nextension FileHandle: IOCloser {}\n"], ["/containerization/Sources/SendablePropertyMacros/SendablePropertyPlugin.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport SwiftCompilerPlugin\nimport SwiftSyntaxMacros\n\n/// A plugin that registers the `SendablePropertyMacroUnchecked` and `SendablePropertyMacro`.\n@main\nstruct SendablePropertyPlugin: CompilerPlugin {\n let providingMacros: [Macro.Type] = [\n SendablePropertyMacroUnchecked.self,\n SendablePropertyMacro.self,\n ]\n}\n"], ["/containerization/Sources/ContainerizationOCI/AnnotationKeys.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// AnnotationKeys contains a subset of \"dictionary keys\" for commonly used annotations in an OCI Image Descriptor\n/// https://github.com/opencontainers/image-spec/blob/main/annotations.md\npublic struct AnnotationKeys: Codable, Sendable {\n public static let containerizationIndexIndirect = \"com.apple.containerization.index.indirect\"\n public static let containerizationImageName = \"com.apple.containerization.image.name\"\n public static let containerdImageName = \"io.containerd.image.name\"\n public static let openContainersImageName = \"org.opencontainers.image.ref.name\"\n}\n"], ["/containerization/vminitd/Sources/vminitd/IOCloser.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nprotocol IOCloser: Sendable {\n var fileDescriptor: Int32 { get }\n\n func close() throws\n}\n"], ["/containerization/Sources/SendableProperty/SendableProperty.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// A declaration of the `@SendableProperty` macro.\n@attached(peer, names: arbitrary)\n@attached(accessor)\npublic macro SendableProperty() = #externalMacro(module: \"SendablePropertyMacros\", type: \"SendablePropertyMacro\")\n"], ["/containerization/Sources/SendableProperty/SendablePropertyUnchecked.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n// A declaration of the `@SendablePropertyUnchecked` macro.\n@attached(peer, names: arbitrary)\n@attached(accessor)\npublic macro SendablePropertyUnchecked() = #externalMacro(module: \"SendablePropertyMacros\", type: \"SendablePropertyMacroUnchecked\")\n"], ["/containerization/vminitd/Sources/vminitd/HostStdio.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nstruct HostStdio: Sendable {\n let stdin: UInt32?\n let stdout: UInt32?\n let stderr: UInt32?\n let terminal: Bool\n}\n"], ["/containerization/Sources/Containerization/VirtualMachineManager.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// A protocol to implement for virtual machine isolated containers.\npublic protocol VirtualMachineManager: Sendable {\n func create(container: Container) throws -> any VirtualMachineInstance\n}\n"], ["/containerization/Sources/Containerization/Image/Unpacker/Unpacker.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport ContainerizationExtras\nimport ContainerizationOCI\nimport Foundation\n\n/// The `Unpacker` protocol defines a standardized interface that involves\n/// decompressing, extracting image layers and preparing it for use.\n///\n/// The `Unpacker` is responsible for managing the lifecycle of the\n/// unpacking process, including any temporary files or resources, until the\n/// `Mount` object is produced.\npublic protocol Unpacker {\n\n /// Unpacks the provided image to a specified path for a given platform.\n ///\n /// This asynchronous method should handle the entire unpacking process, from reading\n /// the `Image` layers for the given `Platform` via its `Manifest`,\n /// to making the extracted contents available as a `Mount`.\n /// Implementations of this method may apply platform-specific optimizations\n /// or transformations during the unpacking.\n ///\n /// Progress updates can be observed via the optional `progress` handler.\n func unpack(_ image: Image, for platform: Platform, at path: URL, progress: ProgressHandler?) async throws -> Mount\n\n}\n"], ["/containerization/Sources/Containerization/VirtualMachineAgent+Additions.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\n/// Protocol to conform to if your agent is capable of relaying unix domain socket\n/// connections.\npublic protocol SocketRelayAgent {\n func relaySocket(port: UInt32, configuration: UnixSocketConfiguration) async throws\n func stopSocketRelay(configuration: UnixSocketConfiguration) async throws\n}\n"], ["/containerization/Sources/Containerization/IO/ReaderStream.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A type that returns a stream of Data.\npublic protocol ReaderStream: Sendable {\n func stream() -> AsyncStream\n}\n"], ["/containerization/Sources/Containerization/IO/Writer.swift", "//===----------------------------------------------------------------------===//\n// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A type that writes the provided Data.\npublic protocol Writer: Sendable {\n func write(_ data: Data) throws\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 03:23:35", "created_task_model": "DeepSeek-R1", "function_skeleton": "@available(macOS, obsoleted: 26, message: \"Use init(address:gateway:reference:macAddress:) instead\")\n public init ( address: String , gateway: String? , macAddress: String? = nil ) { }", "code_description": "This code segment functions to: Provide backward compatibility for object initialization by allowing creation without a required network reference parameter, while deprecating the method for newer operating system versions."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```swift\n[TASK_BEGIN]\n@available(macOS, obsoleted: 26, message: \"Use init(address:gateway:reference:macAddress:) instead\")\npublic init(address: String, gateway: String?, macAddress: String? = nil) {\n var error: vmnet_return_t = 0\n let params = xpc_dictionary_create(nil, nil, 0)\n xpc_dictionary_set_uint64(params, vmnet_operation_mode_key, VMNET_NAT_MODE.rawValue)\n \n let interfaceRef = vmnet_start_interface(params, DispatchQueue.main, &error)\n guard error == VMNET_SUCCESS else {\n fatalError(\"Failed to create vmnet NAT interface: error code \\(error)\")\n }\n \n self.state = Mutex(State(\n address: address,\n gateway: gateway,\n reference: interfaceRef,\n macAddress: macAddress\n ))\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 03-24-23"}, "editdistance_info": {"edit_distance": 29.7143, "calculate_time": "2025-08-21 03:24:23", "true_code_clean": "@available(macOS, obsoleted: 26, message: \"Use init(address:gateway:reference:macAddress:) instead\")\n public init(\n address: String,\n gateway: String?,\n macAddress: String? = nil\n ) {\n let state = State(\n address: address,\n gateway: gateway,\n reference: nil,\n macAddress: macAddress\n )\n self.state = Mutex(state)\n }", "predict_code_clean": "@available(macOS, obsoleted: 26, message: \"Use init(address:gateway:reference:macAddress:) instead\")\npublic init(address: String, gateway: String?, macAddress: String? = nil) {\n var error: vmnet_return_t = 0\n let params = xpc_dictionary_create(nil, nil, 0)\n xpc_dictionary_set_uint64(params, vmnet_operation_mode_key, VMNET_NAT_MODE.rawValue)\n let interfaceRef = vmnet_start_interface(params, DispatchQueue.main, &error)\n guard error == VMNET_SUCCESS else {\n fatalError(\"Failed to create vmnet NAT interface: error code \\(error)\")\n }\n self.state = Mutex(State(\n address: address,\n gateway: gateway,\n reference: interfaceRef,\n macAddress: macAddress\n ))\n}"}}