1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
|
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for Swift project authors
//
internal import _TestingInternals
#if !SWT_NO_PROCESS_SPAWNING
#if SWT_NO_FILE_IO
#error("Platform-specific misconfiguration: support for process spawning requires support for file I/O")
#endif
/// A platform-specific value identifying a process running on the current
/// system.
#if SWT_TARGET_OS_APPLE || os(Linux) || os(FreeBSD)
typealias ProcessID = pid_t
#elseif os(Windows)
typealias ProcessID = HANDLE
#else
#warning("Platform-specific implementation missing: process IDs unavailable")
typealias ProcessID = Never
#endif
/// Spawn a process and wait for it to terminate.
///
/// - Parameters:
/// - executablePath: The path to the executable to spawn.
/// - arguments: The arguments to pass to the executable, not including the
/// executable path.
/// - environment: The environment block to pass to the executable.
/// - standardInput: If not `nil`, a file handle the child process should
/// inherit as its standard input stream. This file handle must be backed
/// by a file descriptor and be open for reading.
/// - standardOutput: If not `nil`, a file handle the child process should
/// inherit as its standard output stream. This file handle must be backed
/// by a file descriptor and be open for writing.
/// - standardError: If not `nil`, a file handle the child process should
/// inherit as its standard error stream. This file handle must be backed
/// by a file descriptor and be open for writing.
/// - additionalFileHandles: A collection of file handles to inherit in the
/// child process.
///
/// - Returns: A value identifying the process that was spawned. The caller must
/// eventually pass this value to ``wait(for:)`` to avoid leaking system
/// resources.
///
/// - Throws: Any error that prevented the process from spawning or its exit
/// condition from being read.
func spawnExecutable(
atPath executablePath: String,
arguments: [String],
environment: [String: String],
standardInput: borrowing FileHandle? = nil,
standardOutput: borrowing FileHandle? = nil,
standardError: borrowing FileHandle? = nil,
additionalFileHandles: [UnsafePointer<FileHandle>] = []
) throws -> ProcessID {
// Darwin and Linux differ in their optionality for the posix_spawn types we
// use, so use this typealias to paper over the differences.
#if SWT_TARGET_OS_APPLE || os(FreeBSD)
typealias P<T> = T?
#elseif os(Linux)
typealias P<T> = T
#endif
#if SWT_TARGET_OS_APPLE || os(Linux) || os(FreeBSD)
return try withUnsafeTemporaryAllocation(of: P<posix_spawn_file_actions_t>.self, capacity: 1) { fileActions in
let fileActions = fileActions.baseAddress!
guard 0 == posix_spawn_file_actions_init(fileActions) else {
throw CError(rawValue: swt_errno())
}
defer {
_ = posix_spawn_file_actions_destroy(fileActions)
}
return try withUnsafeTemporaryAllocation(of: P<posix_spawnattr_t>.self, capacity: 1) { attrs in
let attrs = attrs.baseAddress!
guard 0 == posix_spawnattr_init(attrs) else {
throw CError(rawValue: swt_errno())
}
defer {
_ = posix_spawnattr_destroy(attrs)
}
// Flags to set on the attributes value before spawning the process.
var flags = CShort(0)
// Reset signal handlers to their defaults.
withUnsafeTemporaryAllocation(of: sigset_t.self, capacity: 1) { noSignals in
let noSignals = noSignals.baseAddress!
sigemptyset(noSignals)
posix_spawnattr_setsigmask(attrs, noSignals)
flags |= CShort(POSIX_SPAWN_SETSIGMASK)
}
withUnsafeTemporaryAllocation(of: sigset_t.self, capacity: 1) { allSignals in
let allSignals = allSignals.baseAddress!
sigfillset(allSignals)
posix_spawnattr_setsigdefault(attrs, allSignals);
flags |= CShort(POSIX_SPAWN_SETSIGDEF)
}
// Forward standard I/O streams and any explicitly added file handles.
#if os(Linux) || os(FreeBSD)
var highestFD = CInt(-1)
#endif
func inherit(_ fileHandle: borrowing FileHandle, as standardFD: CInt? = nil) throws {
try fileHandle.withUnsafePOSIXFileDescriptor { fd in
guard let fd else {
throw SystemError(description: "A child process cannot inherit a file handle without an associated file descriptor. Please file a bug report at https://github.com/swiftlang/swift-testing/issues/new")
}
if let standardFD {
_ = posix_spawn_file_actions_adddup2(fileActions, fd, standardFD)
} else {
#if SWT_TARGET_OS_APPLE
_ = posix_spawn_file_actions_addinherit_np(fileActions, fd)
#elseif os(Linux) || os(FreeBSD)
highestFD = max(highestFD, fd)
#endif
}
}
}
func inherit(_ fileHandle: borrowing FileHandle?, as standardFD: CInt? = nil) throws {
if fileHandle != nil {
try inherit(fileHandle!, as: standardFD)
} else if let standardFD {
let mode = (standardFD == STDIN_FILENO) ? O_RDONLY : O_WRONLY
_ = posix_spawn_file_actions_addopen(fileActions, standardFD, "/dev/null", mode, 0)
}
}
try inherit(standardInput, as: STDIN_FILENO)
try inherit(standardOutput, as: STDOUT_FILENO)
try inherit(standardError, as: STDERR_FILENO)
for additionalFileHandle in additionalFileHandles {
try inherit(additionalFileHandle.pointee)
}
#if SWT_TARGET_OS_APPLE
// Close all other file descriptors open in the parent.
flags |= CShort(POSIX_SPAWN_CLOEXEC_DEFAULT)
#elseif os(Linux) || os(FreeBSD)
// This platform doesn't have POSIX_SPAWN_CLOEXEC_DEFAULT, but we can at
// least close all file descriptors higher than the highest inherited one.
// We are assuming here that the caller didn't set FD_CLOEXEC on any of
// these file descriptors.
_ = swt_posix_spawn_file_actions_addclosefrom_np(fileActions, highestFD + 1)
#else
#warning("Platform-specific implementation missing: cannot close unused file descriptors")
#endif
// Set flags; make sure to keep this call below any code that might modify
// the flags mask!
_ = posix_spawnattr_setflags(attrs, flags)
var argv: [UnsafeMutablePointer<CChar>?] = [strdup(executablePath)]
argv += arguments.lazy.map { strdup($0) }
argv.append(nil)
defer {
for arg in argv {
free(arg)
}
}
var environ: [UnsafeMutablePointer<CChar>?] = environment.map { strdup("\($0.key)=\($0.value)") }
environ.append(nil)
defer {
for environ in environ {
free(environ)
}
}
var pid = pid_t()
guard 0 == posix_spawn(&pid, executablePath, fileActions, attrs, argv, environ) else {
throw CError(rawValue: swt_errno())
}
return pid
}
}
#elseif os(Windows)
return try _withStartupInfoEx(attributeCount: 1) { startupInfo in
func inherit(_ fileHandle: borrowing FileHandle, as outWindowsHANDLE: inout HANDLE?) throws {
try fileHandle.withUnsafeWindowsHANDLE { windowsHANDLE in
guard let windowsHANDLE else {
throw SystemError(description: "A child process cannot inherit a file handle without an associated Windows handle. Please file a bug report at https://github.com/swiftlang/swift-testing/issues/new")
}
outWindowsHANDLE = windowsHANDLE
}
}
func inherit(_ fileHandle: borrowing FileHandle?, as outWindowsHANDLE: inout HANDLE?) throws {
if fileHandle != nil {
try inherit(fileHandle!, as: &outWindowsHANDLE)
} else {
outWindowsHANDLE = nil
}
}
// Forward standard I/O streams.
try inherit(standardInput, as: &startupInfo.pointee.StartupInfo.hStdInput)
try inherit(standardOutput, as: &startupInfo.pointee.StartupInfo.hStdOutput)
try inherit(standardError, as: &startupInfo.pointee.StartupInfo.hStdError)
startupInfo.pointee.StartupInfo.dwFlags |= STARTF_USESTDHANDLES
// Ensure standard I/O streams and any explicitly added file handles are
// inherited by the child process.
var inheritedHandles = [HANDLE?](repeating: nil, count: additionalFileHandles.count + 3)
try inherit(standardInput, as: &inheritedHandles[0])
try inherit(standardOutput, as: &inheritedHandles[1])
try inherit(standardError, as: &inheritedHandles[2])
for i in 0 ..< additionalFileHandles.count {
try inherit(additionalFileHandles[i].pointee, as: &inheritedHandles[i + 3])
}
inheritedHandles = inheritedHandles.compactMap(\.self)
return try inheritedHandles.withUnsafeMutableBufferPointer { inheritedHandles in
_ = UpdateProcThreadAttribute(
startupInfo.pointee.lpAttributeList,
0,
swt_PROC_THREAD_ATTRIBUTE_HANDLE_LIST(),
inheritedHandles.baseAddress!,
SIZE_T(MemoryLayout<HANDLE>.stride * inheritedHandles.count),
nil,
nil
)
let commandLine = _escapeCommandLine(CollectionOfOne(executablePath) + arguments)
let environ = environment.map { "\($0.key)=\($0.value)" }.joined(separator: "\0") + "\0\0"
return try commandLine.withCString(encodedAs: UTF16.self) { commandLine in
try environ.withCString(encodedAs: UTF16.self) { environ in
var processInfo = PROCESS_INFORMATION()
guard CreateProcessW(
nil,
.init(mutating: commandLine),
nil,
nil,
true, // bInheritHandles
DWORD(CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT | EXTENDED_STARTUPINFO_PRESENT),
.init(mutating: environ),
nil,
startupInfo.pointer(to: \.StartupInfo)!,
&processInfo
) else {
throw Win32Error(rawValue: GetLastError())
}
_ = CloseHandle(processInfo.hThread)
return processInfo.hProcess!
}
}
}
}
#else
#warning("Platform-specific implementation missing: process spawning unavailable")
throw SystemError(description: "Exit tests are unimplemented on this platform.")
#endif
}
// MARK: -
#if os(Windows)
/// Create a temporary instance of `STARTUPINFOEXW` to pass to
/// `CreateProcessW()`.
///
/// - Parameters:
/// - attributeCount: The number of attributes to make space for in the
/// resulting structure's attribute list.
/// - body: A function to invoke. A temporary, mutable pointer to an instance
/// of `STARTUPINFOEXW` is passed to this function.
///
/// - Returns: Whatever is returned by `body`.
///
/// - Throws: Whatever is thrown while creating the startup info structure or
/// its attribute list, or whatever is thrown by `body`.
private func _withStartupInfoEx<R>(attributeCount: Int = 0, _ body: (UnsafeMutablePointer<STARTUPINFOEXW>) throws -> R) throws -> R {
// Initialize the startup info structure.
var startupInfo = STARTUPINFOEXW()
startupInfo.StartupInfo.cb = DWORD(MemoryLayout.size(ofValue: startupInfo))
guard attributeCount > 0 else {
return try body(&startupInfo)
}
// Initialize an attribute list of sufficient size for the specified number of
// attributes. Alignment is a problem because LPPROC_THREAD_ATTRIBUTE_LIST is
// an opaque pointer and we don't know the alignment of the underlying data.
// We *should* use the alignment of C's max_align_t, but it is defined using a
// C++ using statement on Windows and isn't imported into Swift. So, 16 it is.
var attributeListByteCount = SIZE_T(0)
_ = InitializeProcThreadAttributeList(nil, DWORD(attributeCount), 0, &attributeListByteCount)
return try withUnsafeTemporaryAllocation(byteCount: Int(attributeListByteCount), alignment: 16) { attributeList in
let attributeList = LPPROC_THREAD_ATTRIBUTE_LIST(attributeList.baseAddress!)
guard InitializeProcThreadAttributeList(attributeList, DWORD(attributeCount), 0, &attributeListByteCount) else {
throw Win32Error(rawValue: GetLastError())
}
defer {
DeleteProcThreadAttributeList(attributeList)
}
startupInfo.lpAttributeList = attributeList
return try body(&startupInfo)
}
}
/// Construct an escaped command line string suitable for passing to
/// `CreateProcessW()`.
///
/// - Parameters:
/// - arguments: The arguments, including the executable path, to include in
/// the command line string.
///
/// - Returns: A command line string. This string can later be parsed with
/// `CommandLineToArgvW()`.
///
/// Windows processes are responsible for handling their own command-line
/// escaping. This function is adapted from the code in
/// swift-corelibs-foundation (see `quoteWindowsCommandLine()`) which was
/// itself adapted from code [published by Microsoft](https://learn.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way)
/// (ADO 8992662).
private func _escapeCommandLine(_ arguments: [String]) -> String {
return arguments.lazy
.map { arg in
if !arg.contains(where: {" \t\n\"".contains($0)}) {
return arg
}
var quoted = "\""
var unquoted = arg.unicodeScalars
while !unquoted.isEmpty {
guard let firstNonBackslash = unquoted.firstIndex(where: { $0 != "\\" }) else {
let backslashCount = unquoted.count
quoted.append(String(repeating: "\\", count: backslashCount * 2))
break
}
let backslashCount = unquoted.distance(from: unquoted.startIndex, to: firstNonBackslash)
if (unquoted[firstNonBackslash] == "\"") {
quoted.append(String(repeating: "\\", count: backslashCount * 2 + 1))
quoted.append(String(unquoted[firstNonBackslash]))
} else {
quoted.append(String(repeating: "\\", count: backslashCount))
quoted.append(String(unquoted[firstNonBackslash]))
}
unquoted.removeFirst(backslashCount + 1)
}
quoted.append("\"")
return quoted
}.joined(separator: " ")
}
#endif
#endif
|