-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathConfiguration.swift
More file actions
1576 lines (1420 loc) · 52.7 KB
/
Configuration.swift
File metadata and controls
1576 lines (1420 loc) · 52.7 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)
import System
#else
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 import WinSDK
#endif
internal import Dispatch
import Synchronization
/// 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 will inherit
/// 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 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
}
public init(
_ executable: Executable,
arguments: Arguments = [],
environment: Environment = .inherit,
workingDirectory: FilePath? = nil,
platformOptions: PlatformOptions = PlatformOptions()
) {
self.init(
executable: executable,
arguments: arguments,
environment: environment,
workingDirectory: workingDirectory,
platformOptions: platformOptions
)
}
internal func run<Result>(
input: consuming CreatedPipe,
output: consuming CreatedPipe,
error: consuming CreatedPipe,
isolation: isolated (any Actor)? = #isolation,
_ body: (
(
Execution,
consuming IOChannel?,
consuming IOChannel?,
consuming IOChannel?
) async throws -> Result
)
) async throws -> ExecutionOutcome<Result> {
let spawnResults = try await self.spawn(
withInput: input,
outputPipe: output,
errorPipe: error
)
var spawnResultBox: SpawnResult?? = consume spawnResults
var _spawnResult = spawnResultBox!.take()!
let execution = _spawnResult.execution
defer {
// Close process file descriptor now we finished monitoring
execution.processIdentifier.close()
}
return try await withAsyncTaskCleanupHandler { () throws -> ExecutionOutcome<Result> in
let inputIO = _spawnResult.inputWriteEnd()
let outputIO = _spawnResult.outputReadEnd()
let errorIO = _spawnResult.errorReadEnd()
let result: Swift.Result<Result, any Error>
do {
// Body runs in the same isolation
let bodyResult = try await body(_spawnResult.execution, inputIO, outputIO, errorIO)
result = .success(bodyResult)
} catch {
result = .failure(error)
}
// Ensure that we begin monitoring process termination after `body` runs
// and regardless of whether `body` throws, so that the pid gets reaped
// even if `body` throws, and we are not leaving zombie processes in the
// process table which will cause the process termination monitoring thread
// to effectively hang due to the pid never being awaited
let terminationStatus = try await monitorProcessTermination(
for: execution.processIdentifier
)
return ExecutionOutcome(
terminationStatus: terminationStatus,
value: try result.get()
)
} onCleanup: {
// Attempt to terminate the child process
await execution.runTeardownSequence(
self.platformOptions.teardownSequence
)
}
}
#if !os(Windows)
internal mutating func runPTY<Result>(
pseudoterminalOptions: PseudoterminalOptions,
preferredBufferSize: Int?,
isolation: isolated (any Actor)? = #isolation,
body: (Execution, Pseudoterminal, StandardInputWriter, AsyncBufferSequence) async throws -> Result
) async throws -> ExecutionOutcome<Result> {
// PTY requires a new session
self.platformOptions.createSession = true
// Update environment and insert TERM
self.environment = self.environment.updating(
["TERM": pseudoterminalOptions.terminalType]
)
// Spawn!
var spawnResults = try await self.spawnPTY(
withOptions: pseudoterminalOptions,
preferredBufferSize: preferredBufferSize
)
let execution = spawnResults.execution
defer {
execution.processIdentifier.close()
}
let teardownSequence = self.platformOptions.teardownSequence
return try await withAsyncTaskCleanupHandler {
let result: Swift.Result<Result, any Error>
do {
let bodyResult = try await body(
execution,
spawnResults.pseudoterminal,
spawnResults.inputWriter,
spawnResults.combinedOutputStream
)
result = .success(bodyResult)
} catch {
result = .failure(error)
}
// Ensure that we begin monitoring process termination after `body` runs
// and regardless of whether `body` throws, so that the pid gets reaped
// even if `body` throws, and we are not leaving zombie processes in the
// process table which will cause the process termination monitoring thread
// to effectively hang due to the pid never being awaited
let terminationStatus = try await monitorProcessTermination(
for: execution.processIdentifier
)
// Process has exited. We can/must close parentDescriptor now
try spawnResults.parentDescriptor.safelyClose()
return ExecutionOutcome(
terminationStatus: terminationStatus,
value: try result.get()
)
} onCleanup: {
// Attempt to terminate the child process
await execution.runTeardownSequence(
teardownSequence
)
}
}
#endif
}
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
/// Executable defines how subprocess looks up the executable for execution.
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
}
/// Locate the executable by its name.
/// `Subprocess` will use `PATH` value to
/// determine the full path to the executable.
public static func name(_ executableName: String) -> Self {
return .init(_config: .executable(executableName))
}
/// Locate the executable by its full path.
/// `Subprocess` will use this path directly.
public static func path(_ filePath: FilePath) -> Self {
return .init(_config: .path(filePath))
}
/// Returns the full executable path given the environment value.
public func resolveExecutablePath(in environment: Environment) throws(SubprocessError) -> FilePath {
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?
/// Create an Arguments object using the given literal values
public init(arrayLiteral elements: String...) {
self.storage = elements.map { .string($0) }
self.executablePathOverride = nil
}
/// Create an Arguments object using the given array
public init(_ array: [String]) {
self.storage = array.map { .string($0) }
self.executablePathOverride = nil
}
/// Create an `Argument` object using the given values, but
/// override the first Argument value to `executablePathOverride`.
/// If `executablePathOverride` is nil,
/// `Arguments` will automatically use the executable path
/// as the first argument.
/// - Parameters:
/// - executablePathOverride: the value to override the first argument.
/// - remainingValues: the rest of the argument value
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
/// Create an `Argument` object using the given values, but
/// override the first Argument value to `executablePathOverride`.
/// If `executablePathOverride` is nil,
/// `Arguments` will automatically use the executable path
/// as the first argument.
/// - Parameters:
/// - executablePathOverride: the value to override the first argument.
/// - remainingValues: the rest of the argument value
public init(executablePathOverride: [UInt8]?, remainingValues: [[UInt8]]) {
self.storage = remainingValues.map { .rawBytes($0) }
if let override = executablePathOverride {
self.executablePathOverride = .rawBytes(override)
} else {
self.executablePathOverride = nil
}
}
/// Create an arguments object using 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 executing 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
}
/// Child process should inherit the same environment
/// values from its parent process.
public static var inherit: Self {
return .init(config: .inherit([:]))
}
/// Override the provided `newValue` in the existing `Environment`.
/// Keys with `nil` values in `newValue` will be removed from existing
/// `Environment` before passing to 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
}
}
/// Use custom environment variables
public static func custom(_ newValue: [Key: String]) -> Self {
return .init(config: .custom(newValue))
}
#if !os(Windows)
/// Use custom environment variables of 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
}
}
}
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
/// An exit status of a subprocess.
@frozen
public enum TerminationStatus: Sendable, Hashable {
#if canImport(WinSDK)
/// The type of the status code.
public typealias Code = DWORD
#else
/// The type of the status code.
public typealias Code = CInt
#endif
/// The subprocess was existed with the given code
case exited(Code)
/// The subprocess was signaled with given exception value
case unhandledException(Code)
/// Whether the current TerminationStatus is successful.
public var isSuccess: Bool {
switch self {
case .exited(let exitCode):
return exitCode == 0
case .unhandledException(_):
return false
}
}
}
extension TerminationStatus: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of this termination status.
public var description: String {
switch self {
case .exited(let code):
return "exited(\(code))"
case .unhandledException(let code):
return "unhandledException(\(code))"
}
}
/// A debug-oriented textual representation of this termination status.
public var debugDescription: String {
return self.description
}
}
// MARK: - PTY
#if !os(Windows)
/// Settings to configure the pseudoterminal (PTY) when
/// spawning in PTY mode.
public struct PseudoterminalOptions: Sendable {
/// Terminal mode configuration.
///
/// On Darwin/Linux, this controls the initial `termios` settings applied to the
/// PTY replica fd at spawn time via `openpty()`.
///
/// On Windows (ConPTY), terminal mode is managed internally by the pseudo console.
/// The child process controls its own mode via `SetConsoleMode()`. Therefore only
/// `.cooked` mode is available on Windows
public struct TerminalMode: Sendable {
internal enum Storage: Sendable {
case cooked
case raw
#if !os(Windows)
case custom(termios)
#endif
}
internal let storage: Storage
private init(_ storage: Storage) {
self.storage = storage
}
/// Default cooked mode with kernel line editing, echo, and signal processing.
/// - Darwin/Linux: `TTYDEF_IFLAG`, `TTYDEF_OFLAG`, `TTYDEF_LFLAG`, `TTYDEF_CFLAG`
/// - Windows: ConPTY default (equivalent to `ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT |
/// ENABLE_PROCESSED_INPUT`)
public static var cooked: Self { .init(.cooked) }
#if !os(Windows)
/// Raw mode — all bytes passed through unmodified. Applies `cfmakeraw()` to the PTY.
public static var raw: Self { .init(.raw) }
/// Custom termios configuration
public static func custom(_ info: termios) -> Self {
return .init(.custom(info))
}
#endif
}
/// The initial termianl window size to set to.
public let initialWindowSize: Pseudoterminal.WindowSize
/// The type of this terminal as defined in `terminfo`, used to
/// update TERM environment variable. Terminal type communicates
/// the capabilities, instruction set, and control sequences of a terminal.
public let terminalType: String
/// The initial terminal line discipline mode.
///
/// - `.cooked` (default): Standard terminal behavior with kernel
/// line editing, echo, and signal generation. Use when spawning
/// shells or general-purpose command-line tools.
/// - `.raw`: Passes all bytes through unmodified. Use when the
/// child process manages its own input handling, or when the
/// parent process implements line editing.
///
/// The child process may change this at any time via `tcsetattr`.
/// This setting only controls the initial state at spawn time.
///
/// For more informationm see `cfmakeraw(3)` and `termios(4)`.
public let terminalMode: TerminalMode
public init(
initialWindowSize: Pseudoterminal.WindowSize,
terminalType: String,
terminalMode: TerminalMode = .cooked
) {
self.initialWindowSize = initialWindowSize
self.terminalType = terminalType
self.terminalMode = terminalMode
}
}
/// `Pseudoterminal` is used to get and update terminal information
/// such as window size and terminal type while the child process
/// is running.
public struct Pseudoterminal: Sendable {
/// `WindowSize` defines the dimensions of a terminal window
public struct WindowSize: Sendable {
public let rows: UInt16
public let columns: UInt16
public init(rows: UInt16, columns: UInt16) {
self.rows = rows
self.columns = columns
}
}
/// The dimension of this terminal window
public var windowSize: WindowSize {
get throws {
var result = winsize()
guard ioctl(self.parentDescriptor, UInt(TIOCGWINSZ), &result) == 0 else {
throw SubprocessError.spawnFailed(
withUnderlyingError: .init(rawValue: errno),
reason: "Failed to get window size"
)
}
return WindowSize(rows: result.ws_row, columns: result.ws_col)
}
}
/// The type of this terminal as defined in `terminfo`
public let terminalType: String
private let parentDescriptor: CInt
/// Update the dimension of this terminal window
public func update(windowSize: WindowSize) throws(SubprocessError) {
var winsize = winsize(
ws_row: windowSize.rows,
ws_col: windowSize.columns,
ws_xpixel: 0,
ws_ypixel: 0
)
guard ioctl(self.parentDescriptor, UInt(TIOCSWINSZ), &winsize) == 0 else {
throw SubprocessError.spawnFailed(
withUnderlyingError: .init(rawValue: errno),
reason: "Failed to set window size"
)
}
}
internal init(parentDescriptor: CInt, terminalType: String) {
self.parentDescriptor = parentDescriptor
self.terminalType = terminalType
}
}
#endif
// 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 execution: Execution
var _inputWriteEnd: IOChannel?
var _outputReadEnd: IOChannel?
var _errorReadEnd: IOChannel?
init(
execution: Execution,
inputWriteEnd: consuming IOChannel?,
outputReadEnd: consuming IOChannel?,
errorReadEnd: consuming IOChannel?
) {
self.execution = execution
self._inputWriteEnd = consume inputWriteEnd
self._outputReadEnd = consume outputReadEnd
self._errorReadEnd = consume errorReadEnd
}
mutating func inputWriteEnd() -> IOChannel? {
return self._inputWriteEnd.take()
}
mutating func outputReadEnd() -> IOChannel? {
return self._outputReadEnd.take()
}
mutating func errorReadEnd() -> IOChannel? {
return self._errorReadEnd.take()
}
}
#if !os(Windows)
internal struct SpawnPTYResult: ~Copyable {
let execution: Execution
let pseudoterminal: Pseudoterminal
let inputWriter: StandardInputWriter
let combinedOutputStream: AsyncBufferSequence
var parentDescriptor: IODescriptor
}
#endif
}
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
case dispatchIO(DispatchIO)
}
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(rawValue: error)
)
throw subprocessError
}