-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathConfiguration.swift
More file actions
1448 lines (1312 loc) · 49.9 KB
/
Configuration.swift
File metadata and controls
1448 lines (1312 loc) · 49.9 KB
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2025 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
//
//===----------------------------------------------------------------------===//
#if canImport(System)
public import System
#else
public import SystemPackage
#endif
#if canImport(Darwin)
import Darwin
#elseif canImport(Android)
import Android
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(WinSDK)
@preconcurrency public import WinSDK
#endif
/// A collection of configuration parameters to use when
/// spawning a subprocess.
public struct Configuration: Sendable {
/// The executable to run.
public var executable: Executable
/// The arguments to pass to the executable.
public var arguments: Arguments
/// The environment to use when running the executable.
public var environment: Environment
/// The working directory to use when running the executable.
///
/// If this property is `nil`, the subprocess inherits the working
/// directory from the parent process.
public var workingDirectory: FilePath?
/// The platform-specific options to use when
/// running the subprocess.
public var platformOptions: PlatformOptions
/// Creates a configuration with the parameters you provide.
/// - Parameters:
/// - executable: The executable to run.
/// - arguments: The arguments to pass to the executable.
/// - environment: The environment to use when running the executable.
/// - workingDirectory: The working directory to use when running the executable.
/// - platformOptions: The platform-specific options to use when running the subprocess.
public init(
executable: Executable,
arguments: Arguments = [],
environment: Environment = .inherit,
workingDirectory: FilePath? = nil,
platformOptions: PlatformOptions = PlatformOptions()
) {
self.executable = executable
self.arguments = arguments
self.environment = environment
self.workingDirectory = workingDirectory
self.platformOptions = platformOptions
}
internal func run<Result, Input: InputProtocol, Output: OutputProtocol, Error: OutputProtocol>(
input: consuming CreatedPipe,
as inputType: Input.Type,
output: consuming CreatedPipe,
as outputType: Output.Type,
error: consuming CreatedPipe,
as errorType: Error.Type,
_ body: (
(
ProcessIdentifier,
consuming IODescriptor?,
consuming IODescriptor?,
consuming IODescriptor?
) async throws -> Result
)
) async throws -> ExecutionOutcome<Result> {
// Built before spawning so it can be attached to spawn failures, where
// no resolved values exist yet.
let baseContext = ExecutionContext(self)
var spawnResults: SpawnResult
#if os(Windows)
// `spawn` is `throws(SubprocessError)` on Windows, so `error` is
// already typed; an `as SubprocessError` pattern is a redundant cast
// that crashes the 6.2 toolchain's SIL ownership verifier. Elsewhere
// `spawn` is untyped `throws`, where the cast is meaningful.
do {
spawnResults = try await self.spawn(
withInput: input,
outputPipe: output,
errorPipe: error
)
} catch {
throw error.withExecutionContext(baseContext)
}
#else
do {
spawnResults = try await self.spawn(
withInput: input,
outputPipe: output,
errorPipe: error
)
} catch let error as SubprocessError {
throw error.withExecutionContext(baseContext)
}
#endif
let processIdentifier = spawnResults.processIdentifier
defer {
// Close the process file descriptor now that monitoring has finished.
processIdentifier.close()
}
// Spawn succeeded, so resolved values are available. This context is
// attached to any error surfacing after spawn.
let executionContext = ExecutionContext(
self,
resolvedExecutable: spawnResults.resolvedExecutable,
resolvedEnvironment: self.environment.resolvedValues(),
resolvedWorkingDirectory: self.workingDirectory ?? currentWorkingDirectory()
)
do {
return try await withAsyncTaskCleanupHandler { () throws -> ExecutionOutcome<Result> in
// The counter coordinates a race between two finishers: the body
// closure and the process-termination monitor. Whichever side
// increments first observes a value of `1` and owns the response;
// the other side sees `2` and stays out of the way.
//
// If the monitor wins, the child has exited while the body is
// still reading or writing. The body might be blocked on a pipe
// that an inherited grandchild keeps open, so the monitor calls
// `cancelAsyncIO` to unblock it. If the body wins, the I/O
// already finished cleanly and no cancellation is needed.
let taskFinishFlag = AtomicCounter()
let (result, monitorError) = try await withThrowingTaskGroup(
of: SubprocessError?.self,
returning: (Swift.Result<Result, any Swift.Error>, SubprocessError?).self
) { group in
group.addTask {
do throws(SubprocessError) {
try await waitForProcessTermination(for: processIdentifier)
if taskFinishFlag.addOne() == 1 {
// The body closure hasn't finished but the child
// process has terminated. Cancel all active
// AsyncIO now.
try AsyncIO.shared.cancelAsyncIO(for: processIdentifier)
}
return nil
} catch {
try? AsyncIO.shared.cancelAsyncIO(for: processIdentifier)
return error
}
}
let inputIO = spawnResults.inputWriteEnd()
let outputIO = spawnResults.outputReadEnd()
let errorIO = spawnResults.errorReadEnd()
let result: Swift.Result<Result, any Swift.Error>
do {
// Body runs in the same isolation.
let bodyResult = try await body(processIdentifier, inputIO, outputIO, errorIO)
taskFinishFlag.addOne()
result = .success(bodyResult)
} catch {
let execution = Execution<Input, Output, Error>(
processIdentifier: processIdentifier,
inputWriter: nil,
outputStream: nil,
errorStream: nil
)
// Attempt to terminate the child process when the body throws
await execution.teardown(using: self.platformOptions.teardownSequence)
result = .failure(error)
}
// Wait for the monitor child task to finish.
let monitorError = try await group.next() ?? nil
return (result, monitorError)
}
// Drop the cancellation marker before reaping the zombie. After
// `reapProcess` runs the kernel can immediately reuse this PID,
// so the marker must be gone first; otherwise a concurrent
// `run()` that happens to inherit the same PID would see the
// stale entry and reject its registrations.
AsyncIO.shared.cleanup(processIdentifier: processIdentifier)
let terminationStatus = try reapProcess(with: processIdentifier)
if let monitorError {
throw monitorError
}
return try ExecutionOutcome(
terminationStatus: terminationStatus,
value: result.get()
)
} onCleanup: {
let execution = Execution<Input, Output, Error>(
processIdentifier: processIdentifier,
inputWriter: nil,
outputStream: nil,
errorStream: nil
)
// Attempt to terminate the child process.
await execution.teardown(using: self.platformOptions.teardownSequence)
}
} catch let error as SubprocessError {
throw error.withExecutionContext(executionContext)
}
}
}
extension Configuration: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of this configuration.
public var description: String {
return """
Configuration(
executable: \(self.executable.description),
arguments: \(self.arguments.description),
environment: \(self.environment.description),
workingDirectory: \(self.workingDirectory?.string ?? ""),
platformOptions: \(self.platformOptions.description(withIndent: 1))
)
"""
}
/// A debug-oriented textual representation of this configuration.
public var debugDescription: String {
return """
Configuration(
executable: \(self.executable.debugDescription),
arguments: \(self.arguments.debugDescription),
environment: \(self.environment.debugDescription),
workingDirectory: \(self.workingDirectory?.string ?? ""),
platformOptions: \(self.platformOptions.description(withIndent: 1))
)
"""
}
}
// MARK: - Cleanup
extension Configuration {
/// Close each input individually, and throw the first error if there's multiple errors thrown
@Sendable
internal func safelyCloseMultiple(
inputRead: consuming IODescriptor?,
inputWrite: consuming IODescriptor?,
outputRead: consuming IODescriptor?,
outputWrite: consuming IODescriptor?,
errorRead: consuming IODescriptor?,
errorWrite: consuming IODescriptor?
) throws(SubprocessError) {
var possibleError: SubprocessError? = nil
// To avoid closing the same descriptor multiple times,
// keep track of the list of descriptors that we have
// already closed. If a `IODescriptor.Descriptor` is
// already closed, mark that `IODescriptor` as closed
// as opposed to actually try to close it.
var remainingSet: Set<IODescriptor.Descriptor> = Set(
optionalSequence: [
inputRead?.descriptor(),
inputWrite?.descriptor(),
outputRead?.descriptor(),
outputWrite?.descriptor(),
errorRead?.descriptor(),
errorWrite?.descriptor(),
]
)
do {
if remainingSet.tryRemove(inputRead?.descriptor()) {
try inputRead?.safelyClose()
} else {
try inputRead?.markAsClosed()
}
} catch {
possibleError = error
}
do {
if remainingSet.tryRemove(inputWrite?.descriptor()) {
try inputWrite?.safelyClose()
} else {
try inputWrite?.markAsClosed()
}
} catch {
possibleError = error
}
do {
if remainingSet.tryRemove(outputRead?.descriptor()) {
try outputRead?.safelyClose()
} else {
try outputRead?.markAsClosed()
}
} catch {
possibleError = error
}
do {
if remainingSet.tryRemove(outputWrite?.descriptor()) {
try outputWrite?.safelyClose()
} else {
try outputWrite?.markAsClosed()
}
} catch {
possibleError = error
}
do {
if remainingSet.tryRemove(errorRead?.descriptor()) {
try errorRead?.safelyClose()
} else {
try errorRead?.markAsClosed()
}
} catch {
possibleError = error
}
do {
if remainingSet.tryRemove(errorWrite?.descriptor()) {
try errorWrite?.safelyClose()
} else {
try errorWrite?.markAsClosed()
}
} catch {
possibleError = error
}
if let actualError = possibleError {
throw actualError
}
}
}
// MARK: - Executable
/// A description of how to locate the executable to run.
public struct Executable: Sendable, Hashable {
internal enum Storage: Sendable, Hashable {
case executable(String)
case path(FilePath)
}
internal let storage: Storage
private init(_config: Storage) {
self.storage = _config
}
/// Locates the executable by name.
/// The subprocess uses the `PATH` value to determine the full path.
public static func name(_ executableName: String) -> Self {
return .init(_config: .executable(executableName))
}
/// Locates the executable by its full file path.
/// The subprocess uses this path directly.
public static func path(_ filePath: FilePath) -> Self {
return .init(_config: .path(filePath))
}
/// Resolves the full executable path using the given environment.
public func resolveExecutablePath(in environment: Environment) async throws(SubprocessError) -> FilePath {
try await runOnBackgroundThread { () throws(SubprocessError) -> FilePath in
let path = try self.resolveExecutablePath(withPathValue: environment.pathValue())
return FilePath(path)
}
}
}
extension Executable: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of this executable.
public var description: String {
switch storage {
case .executable(let executableName):
return executableName
case .path(let filePath):
return filePath.string
}
}
/// A debug-oriented textual representation of this executable.
public var debugDescription: String {
switch storage {
case .executable(let string):
return "executable(\(string))"
case .path(let filePath):
return "path(\(filePath.string))"
}
}
}
// MARK: - Arguments
/// A collection of arguments to pass to the subprocess.
public struct Arguments: Sendable, ExpressibleByArrayLiteral, Hashable {
/// The type of the elements of an array literal.
public typealias ArrayLiteralElement = String
internal let storage: [StringOrRawBytes]
internal let executablePathOverride: StringOrRawBytes?
/// Creates an arguments value from the given literal values.
public init(arrayLiteral elements: String...) {
self.storage = elements.map { .string($0) }
self.executablePathOverride = nil
}
/// Creates an arguments value from the given array.
public init(_ array: [String]) {
self.storage = array.map { .string($0) }
self.executablePathOverride = nil
}
/// Creates an ``Arguments`` value using the given values, but
/// override the first argument value with `executablePathOverride`.
/// If `executablePathOverride` is `nil`,
/// ``Arguments`` automatically uses the executable path
/// as the first argument.
/// - Parameters:
/// - executablePathOverride: The value to override the first argument.
/// - remainingValues: The remaining argument values.
public init(executablePathOverride: String?, remainingValues: [String]) {
self.storage = remainingValues.map { .string($0) }
if let executablePathOverride = executablePathOverride {
self.executablePathOverride = .string(executablePathOverride)
} else {
self.executablePathOverride = nil
}
}
#if !os(Windows) // Windows does not support non-unicode arguments
/// Creates an ``Arguments`` value using the given values, but
/// override the first argument value with `executablePathOverride`.
/// If `executablePathOverride` is `nil`,
/// ``Arguments`` automatically uses the executable path
/// as the first argument.
/// - Parameters:
/// - executablePathOverride: The value to override the first argument.
/// - remainingValues: The remaining argument values.
public init(executablePathOverride: [UInt8]?, remainingValues: [[UInt8]]) {
self.storage = remainingValues.map { .rawBytes($0) }
if let override = executablePathOverride {
self.executablePathOverride = .rawBytes(override)
} else {
self.executablePathOverride = nil
}
}
/// Creates an arguments value from the array you provide.
public init(_ array: [[UInt8]]) {
self.storage = array.map { .rawBytes($0) }
self.executablePathOverride = nil
}
#endif
}
extension Arguments: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of the arguments.
public var description: String {
var result: [String] = self.storage.map(\.description)
if let override = self.executablePathOverride {
result.insert("override\(override.description)", at: 0)
}
return result.description
}
/// A debug-oriented textual representation of the arguments.
public var debugDescription: String { return self.description }
}
// MARK: - Environment
/// A set of environment variables to use when running the subprocess.
public struct Environment: Sendable, Hashable {
internal enum Configuration: Sendable, Hashable {
case inherit([Key: String?])
case custom([Key: String])
#if !os(Windows)
case rawBytes([[UInt8]])
#endif
}
internal let config: Configuration
init(config: Configuration) {
self.config = config
}
/// Inherits the environment from the current process.
public static var inherit: Self {
return .init(config: .inherit([:]))
}
/// Returns an updated environment that applies `newValue` to the current configuration.
///
/// Keys with `nil` values in `newValue` remove the corresponding entry
/// from the environment before passing it to the child process.
public func updating(_ newValue: [Key: String?]) -> Self {
switch config {
case .inherit(var overrides):
for (key, value) in newValue {
overrides[key] = value
}
return .init(config: .inherit(overrides))
case .custom(var environment):
for (key, value) in newValue {
environment[key] = value
}
return .init(config: .custom(environment))
#if !os(Windows)
case .rawBytes(var rawBytesArray):
let overriddenKeys = newValue.keys.map { Array("\($0)=".utf8) }
rawBytesArray.removeAll {
overriddenKeys.contains(where: $0.starts)
}
for (key, value) in newValue {
if let value {
rawBytesArray.append(Array("\(key)=\(value)\0".utf8))
}
}
return .init(config: .rawBytes(rawBytesArray))
#endif
}
}
/// Creates an environment with custom variables.
public static func custom(_ newValue: [Key: String]) -> Self {
return .init(config: .custom(newValue))
}
#if !os(Windows)
/// Creates an environment with custom variables as raw bytes.
public static func custom(_ newValue: [[UInt8]]) -> Self {
return .init(config: .rawBytes(newValue))
}
#endif
}
extension Environment: CustomStringConvertible, CustomDebugStringConvertible {
/// A key used to access values in an ``Environment``.
///
/// This type respects the compiled platform's case sensitivity requirements.
public struct Key {
public let rawValue: String
package init(_ rawValue: String) {
self.rawValue = rawValue
}
}
/// A textual representation of the environment.
public var description: String {
switch self.config {
case .custom(let customDictionary):
return """
Custom environment:
\(customDictionary)
"""
case .inherit(let updateValue):
return """
Inheriting current environment with updates:
\(updateValue)
"""
#if !os(Windows)
case .rawBytes(let rawBytes):
return """
Raw bytes:
\(rawBytes)
"""
#endif
}
}
/// A debug-oriented textual representation of the environment.
public var debugDescription: String {
return self.description
}
internal static func currentEnvironmentValues() -> [Key: String] {
return self.withCopiedEnv { environments in
var results: [Key: String] = [:]
for env in environments {
let environmentString = String(cString: env)
#if os(Windows)
// Windows GetEnvironmentStringsW API can return
// magic environment variables set by the cmd shell
// that starts with `=`
// We should exclude these values
if environmentString.utf8.first == Character("=").utf8.first {
continue
}
#endif // os(Windows)
guard let delimiter = environmentString.firstIndex(of: "=") else {
continue
}
let key = String(environmentString[environmentString.startIndex..<delimiter])
let value = String(
environmentString[environmentString.index(after: delimiter)..<environmentString.endIndex]
)
results[Key(key)] = value
}
return results
}
}
/// The concrete environment variables passed to the child process, or
/// `nil` if they cannot be represented as a `[Key: String]` map.
///
/// This mirrors the environment built by the platform spawn path: for
/// `.inherit`, the parent's current values with the configured overrides
/// applied (a `nil` override removes the key); for `.custom`, those values
/// directly; for raw-byte environments, `nil`. On Windows, `PATH` is
/// injected from the parent when absent, matching the spawn path's
/// DLL-resolution behavior.
internal func resolvedValues() -> [Environment.Key: String]? {
var values: [Environment.Key: String]
switch self.config {
case .custom(let customValues):
values = customValues
case .inherit(let overrides):
values = Self.currentEnvironmentValues()
for (key, override) in overrides {
values[key] = override
}
#if !os(Windows)
case .rawBytes:
return nil
#endif
}
#if os(Windows)
if values[.path] == nil,
let parentPath = Self.currentEnvironmentValues()[.path]
{
values[.path] = parentPath
}
#endif
return values
}
}
extension Environment.Key {
package static let path: Self = "PATH"
}
extension Environment.Key: CodingKeyRepresentable {}
extension Environment.Key: Comparable {
public static func < (lhs: Self, rhs: Self) -> Bool {
// Even on windows use a stable sort order.
lhs.rawValue < rhs.rawValue
}
}
extension Environment.Key: CustomStringConvertible {
public var description: String { self.rawValue }
}
extension Environment.Key: Encodable {
public func encode(to encoder: any Swift.Encoder) throws {
try self.rawValue.encode(to: encoder)
}
}
extension Environment.Key: Equatable {
public static func == (_ lhs: Self, _ rhs: Self) -> Bool {
#if os(Windows)
lhs.rawValue.lowercased() == rhs.rawValue.lowercased()
#else
lhs.rawValue == rhs.rawValue
#endif
}
}
extension Environment.Key: ExpressibleByStringLiteral {
public init(stringLiteral rawValue: String) {
self.init(rawValue)
}
}
extension Environment.Key: Decodable {
public init(from decoder: any Swift.Decoder) throws {
self.rawValue = try String(from: decoder)
}
}
extension Environment.Key: Hashable {
public func hash(into hasher: inout Hasher) {
#if os(Windows)
self.rawValue.lowercased().hash(into: &hasher)
#else
self.rawValue.hash(into: &hasher)
#endif
}
}
extension Environment.Key: RawRepresentable {
public init?(rawValue: String) {
self.rawValue = rawValue
}
}
extension Environment.Key: Sendable {}
// MARK: - TerminationStatus
/// The exit status of a subprocess.
public enum TerminationStatus: Sendable, Hashable {
#if os(Windows)
/// The type of the status code.
public typealias Code = DWORD
#else
/// The type of the status code.
public typealias Code = CInt
#endif
/// The subprocess exited with the given code.
case exited(Code)
#if !os(Windows)
/// The subprocess terminated due to the given signal.
case signaled(Code)
#endif
/// A Boolean value that indicates whether the termination was successful.
public var isSuccess: Bool {
switch self {
case .exited(let exitCode):
return exitCode == 0
#if !os(Windows)
case .signaled(_):
return false
#endif
}
}
}
extension TerminationStatus: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of this termination status.
public var description: String {
switch self {
case .exited(let code):
return "exited(\(code))"
#if !os(Windows)
case .signaled(let code):
return "signaled(\(code))"
#endif
}
}
/// A debug-oriented textual representation of this termination status.
public var debugDescription: String {
return self.description
}
}
// MARK: - Internal
extension Configuration {
/// After Spawn finishes, child side file descriptors
/// (input read, output write, error write) will be closed
/// by `spawn()`. It returns the parent side file descriptors
/// via `SpawnResult` to perform actual reads
internal struct SpawnResult: ~Copyable {
let processIdentifier: ProcessIdentifier
let resolvedExecutable: FilePath?
var _inputWriteEnd: IODescriptor?
var _outputReadEnd: IODescriptor?
var _errorReadEnd: IODescriptor?
init(
processIdentifier: ProcessIdentifier,
inputWriteEnd: consuming IODescriptor?,
outputReadEnd: consuming IODescriptor?,
errorReadEnd: consuming IODescriptor?,
resolvedExecutable: FilePath? = nil
) {
self.processIdentifier = processIdentifier
self._inputWriteEnd = consume inputWriteEnd
self._outputReadEnd = consume outputReadEnd
self._errorReadEnd = consume errorReadEnd
self.resolvedExecutable = resolvedExecutable
}
mutating func inputWriteEnd() -> IODescriptor? {
return self._inputWriteEnd.take()
}
mutating func outputReadEnd() -> IODescriptor? {
return self._outputReadEnd.take()
}
mutating func errorReadEnd() -> IODescriptor? {
return self._errorReadEnd.take()
}
}
}
internal enum StringOrRawBytes: Sendable, Hashable {
case string(String)
case rawBytes([UInt8])
// Return value needs to be deallocated manually by callee
func createRawBytes() -> UnsafeMutablePointer<CChar> {
switch self {
case .string(let string):
#if os(Windows)
return _strdup(string)
#else
return strdup(string)
#endif
case .rawBytes(let rawBytes):
#if os(Windows)
return _strdup(rawBytes)
#else
return strdup(rawBytes)
#endif
}
}
var stringValue: String? {
switch self {
case .string(let string):
return string
case .rawBytes(let rawBytes):
return String(decoding: rawBytes, as: UTF8.self)
}
}
var description: String {
switch self {
case .string(let string):
return string
case .rawBytes(let bytes):
return bytes.description
}
}
var count: Int {
switch self {
case .string(let string):
return string.count
case .rawBytes(let rawBytes):
return strnlen(rawBytes, Int.max)
}
}
func hash(into hasher: inout Hasher) {
// If Raw bytes is valid UTF8, hash it as so
switch self {
case .string(let string):
hasher.combine(string)
case .rawBytes(let bytes):
if let stringValue = self.stringValue {
hasher.combine(stringValue)
} else {
hasher.combine(bytes)
}
}
}
}
internal enum _CloseTarget {
#if canImport(WinSDK)
case handle(HANDLE)
#else
case fileDescriptor(FileDescriptor)
#endif
}
internal func _safelyClose(_ target: _CloseTarget) throws(SubprocessError) {
switch target {
#if os(Windows)
case .handle(let handle):
/// Windows does not provide a “deregistration” API (the reverse of
/// `CreateIoCompletionPort`) for handles and it reuses HANDLE
/// values once they are closed. Since we rely on the handle value
/// as the completion key for `CreateIoCompletionPort`, we should
/// remove the registration when the handle is closed to allow
/// new registration to proceed if the handle is reused.
AsyncIO.shared.removeRegistration(for: handle)
guard CloseHandle(handle) else {
let error = GetLastError()
// Getting `ERROR_INVALID_HANDLE` suggests that the file descriptor
// might have been closed unexpectedly. This can pose security risks
// if another part of the code inadvertently reuses the same HANDLE.
// We use `fatalError` upon receiving `ERROR_INVALID_HANDLE`
// to prevent accidentally closing a different HANDLE.
guard error != ERROR_INVALID_HANDLE else {
fatalError(
"HANDLE \(handle) is already closed"
)
}
let subprocessError: SubprocessError = .asyncIOFailed(
reason: "Failed to close HANDLE",
underlyingError: SubprocessError.WindowsError(win32Error: error)
)
throw subprocessError
}
#else
case .fileDescriptor(let fileDescriptor):
do {
try fileDescriptor.close()
} catch {
guard let errno: Errno = error as? Errno else {
throw .asyncIOFailed(
reason: "Failed to close file descriptor \(fileDescriptor.rawValue)"
)
}
// Getting `.badFileDescriptor` suggests that the file descriptor
// might have been closed unexpectedly. This can pose security risks
// if another part of the code inadvertently reuses the same file descriptor
// number. This problem is especially concerning on Unix systems due to POSIX’s
// guarantee of using the lowest available file descriptor number, making reuse
// more probable. We use `fatalError` upon receiving `.badFileDescriptor`
// to prevent accidentally closing a different file descriptor.
guard errno != .badFileDescriptor else {
fatalError(
"FileDescriptor \(fileDescriptor.rawValue) is already closed"
)
}
// Throw other kinds of errors to allow user to catch them
throw .asyncIOFailed(
reason: "Failed to close file descriptor \(fileDescriptor.rawValue)",
underlyingError: errno
)
}
#endif
}
}
/// An IO descriptor wraps platform-specific file descriptor, which establishes a
/// connection to the standard input/output (IO) system during the process of
/// spawning a child process.
///
/// Unlike a file descriptor, the `IODescriptor` does not support
/// data read/write operations; its primary function is to facilitate the spawning of
/// child processes by providing a platform-specific file descriptor.
internal struct IODescriptor: ~Copyable {
#if canImport(WinSDK)
typealias Descriptor = HANDLE
#else
typealias Descriptor = FileDescriptor
#endif
internal var closeWhenDone: Bool
#if canImport(WinSDK)
internal nonisolated(unsafe) let _descriptor: Descriptor
#else
internal let _descriptor: Descriptor
#endif
internal init(
_ descriptor: Descriptor,
closeWhenDone: Bool
) {
self._descriptor = descriptor
self.closeWhenDone = closeWhenDone
}
internal init?(duplicating ioDescriptor: borrowing IODescriptor?) throws(SubprocessError) {
let descriptor = try ioDescriptor?.duplicate()
if let descriptor {
self = descriptor
} else {
return nil
}
}
func duplicate() throws(SubprocessError) -> IODescriptor {
do throws(any Error) {
return try IODescriptor(self._descriptor.duplicate(), closeWhenDone: self.closeWhenDone)
} catch {
throw SubprocessError.asyncIOFailed(
reason: "Failed to duplicate file descriptor \(self._descriptor)",
underlyingError: error as? SubprocessError.UnderlyingError
)
}
}
internal mutating func safelyClose() throws(SubprocessError) {
guard self.closeWhenDone else {
return
}
closeWhenDone = false
#if canImport(WinSDK)
try _safelyClose(.handle(self._descriptor))
#else
try _safelyClose(.fileDescriptor(self._descriptor))
#endif
}