-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathSubprocess+Windows.swift
More file actions
1735 lines (1616 loc) · 74.6 KB
/
Subprocess+Windows.swift
File metadata and controls
1735 lines (1616 loc) · 74.6 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(WinSDK)
@preconcurrency public import WinSDK
#if canImport(System)
import System
#else
import SystemPackage
#endif
import _SubprocessCShims
// Windows-specific implementation
extension Configuration {
// @unchecked Sendable because we need to capture UnsafePointers
// to send to another thread. While UnsafePointers are not
// Sendable, we are not mutating them -- we only need these type
// for C interface.
internal struct SpawnContext: @unchecked Sendable {
let startupInfo: UnsafeMutablePointer<STARTUPINFOEXW>
let createProcessFlags: DWORD
}
internal func spawn(
withInput inputPipe: consuming CreatedPipe,
outputPipe: consuming CreatedPipe,
errorPipe: consuming CreatedPipe
) async throws(SubprocessError) -> SpawnResult {
let inputReadFileDescriptor: IODescriptor? = inputPipe.readFileDescriptor()
let inputWriteFileDescriptor: IODescriptor? = inputPipe.writeFileDescriptor()
let outputReadFileDescriptor: IODescriptor? = outputPipe.readFileDescriptor()
let outputWriteFileDescriptor: IODescriptor? = outputPipe.writeFileDescriptor()
let errorReadFileDescriptor: IODescriptor? = errorPipe.readFileDescriptor()
let errorWriteFileDescriptor: IODescriptor? = errorPipe.writeFileDescriptor()
// Create the Job Object up front. It persists across all candidate path
// attempts, and is owned by this function until ownership transfers to
// the `ProcessIdentifier` on the success path.
let jobHandle = try Self.createJobObject()
var jobHandleOwned = true
defer {
if jobHandleOwned {
_ = CloseHandle(jobHandle)
}
}
// CreateProcessW supports using `lpApplicationName` as well as `lpCommandLine` to
// specify executable path. However, only `lpCommandLine` supports PATH looking up,
// whereas `lpApplicationName` does not. In general we should rely on `lpCommandLine`'s
// automatic PATH lookup so we only need to call `CreateProcessW` once. However, if
// user wants to override executable path in arguments, we have to use `lpApplicationName`
// to specify the executable path. In this case, manually loop over all possible paths.
let possibleExecutablePaths: _OrderedSet<String>
if _fastPath(self.arguments.executablePathOverride == nil) {
// Fast path: we can rely on `CreateProcessW`'s built in Path searching
switch self.executable.storage {
case .executable(let executable):
possibleExecutablePaths = _OrderedSet([executable])
case .path(let path):
possibleExecutablePaths = _OrderedSet([path.string])
}
} else {
// Slow path: user requested arg0 override, therefore we must manually
// traverse through all possible executable paths
possibleExecutablePaths = self.executable.possibleExecutablePaths(
withPathValue: self.environment.pathValue()
)
}
for executablePath in possibleExecutablePaths {
let applicationName: String?
let commandAndArgs: String
let environment: String
let intendedWorkingDir: String?
do {
(
applicationName,
commandAndArgs,
environment,
intendedWorkingDir
) = try self.preSpawn(withPossibleExecutablePath: executablePath)
} catch {
try self.safelyCloseMultiple(
inputRead: inputReadFileDescriptor,
inputWrite: inputWriteFileDescriptor,
outputRead: outputReadFileDescriptor,
outputWrite: outputWriteFileDescriptor,
errorRead: errorReadFileDescriptor,
errorWrite: errorWriteFileDescriptor
)
throw error
}
var createProcessFlags = self.generateCreateProcessFlag()
let (created, processInfo, windowsError, userManagesResume): (Bool, PROCESS_INFORMATION, DWORD, Bool)
do {
(created, processInfo, windowsError, userManagesResume) = try await self.withStartupInfoEx(
inputRead: inputReadFileDescriptor,
inputWrite: inputWriteFileDescriptor,
outputRead: outputReadFileDescriptor,
outputWrite: outputWriteFileDescriptor,
errorRead: errorReadFileDescriptor,
errorWrite: errorWriteFileDescriptor
) { startupInfo throws(SubprocessError) in
// Give calling process a chance to modify flag and startup info
if let configurator = self.platformOptions.preSpawnProcessConfigurator {
try configurator(&createProcessFlags, &startupInfo.pointer(to: \.StartupInfo)!.pointee)
}
// If the configurator set `CREATE_SUSPENDED`, the user has
// explicitly opted into managing the child's initial
// resume themselves. Otherwise, Subprocess resumes the
// child after assigning it to the Job Object.
let userManagesResume = (createProcessFlags & DWORD(CREATE_SUSPENDED)) != 0
// Subprocess assigns every spawned child to a Job Object
// before any user code runs in the child. `CREATE_SUSPENDED`
// makes the assignment atomic, so it is always set
// regardless of what the configurator did.
createProcessFlags |= DWORD(CREATE_SUSPENDED)
let spawnContext = SpawnContext(
startupInfo: startupInfo,
createProcessFlags: createProcessFlags
)
// Spawn (featuring pyramid!)
return try await runOnBackgroundThread { () throws(SubprocessError) in
try applicationName.withOptionalNTPathRepresentation { applicationNameW throws(SubprocessError) in
try commandAndArgs._withCString(
encodedAs: UTF16.self
) { commandAndArgsW throws(SubprocessError) in
try environment._withCString(
encodedAs: UTF16.self
) { environmentW throws(SubprocessError) in
try intendedWorkingDir.withOptionalNTPathRepresentation { intendedWorkingDirW throws(SubprocessError) in
// Spawn differently depending on whether
// we need to spawn as a user
if let userCredentials = self.platformOptions.userCredentials {
return try userCredentials.username._withCString(
encodedAs: UTF16.self
) { usernameW throws(SubprocessError) in
try userCredentials.password._withCString(
encodedAs: UTF16.self
) { passwordW throws(SubprocessError) in
try userCredentials.domain.withOptionalCString(
encodedAs: UTF16.self
) { domainW throws(SubprocessError) in
var processInfo = PROCESS_INFORMATION()
let created = CreateProcessWithLogonW(
usernameW,
domainW,
passwordW,
DWORD(LOGON_WITH_PROFILE),
applicationNameW,
UnsafeMutablePointer<WCHAR>(mutating: commandAndArgsW),
spawnContext.createProcessFlags,
UnsafeMutableRawPointer(mutating: environmentW),
intendedWorkingDirW,
spawnContext.startupInfo.pointer(to: \.StartupInfo)!,
&processInfo
)
return (created, processInfo, GetLastError(), userManagesResume)
}
}
}
}
var processInfo = PROCESS_INFORMATION()
let result = CreateProcessW(
applicationNameW,
UnsafeMutablePointer<WCHAR>(mutating: commandAndArgsW),
nil, // lpProcessAttributes
nil, // lpThreadAttributes
true, // bInheritHandles
spawnContext.createProcessFlags,
UnsafeMutableRawPointer(mutating: environmentW),
intendedWorkingDirW,
spawnContext.startupInfo.pointer(to: \.StartupInfo)!,
&processInfo
)
return (result, processInfo, GetLastError(), userManagesResume)
}
}
}
}
}
}
} catch {
try self.safelyCloseMultiple(
inputRead: inputReadFileDescriptor,
inputWrite: inputWriteFileDescriptor,
outputRead: outputReadFileDescriptor,
outputWrite: outputWriteFileDescriptor,
errorRead: errorReadFileDescriptor,
errorWrite: errorWriteFileDescriptor
)
throw error
}
guard created else {
if windowsError == ERROR_FILE_NOT_FOUND || windowsError == ERROR_PATH_NOT_FOUND {
// This executable path is not it. Try the next one
continue
}
try self.safelyCloseMultiple(
inputRead: inputReadFileDescriptor,
inputWrite: inputWriteFileDescriptor,
outputRead: outputReadFileDescriptor,
outputWrite: outputWriteFileDescriptor,
errorRead: errorReadFileDescriptor,
errorWrite: errorWriteFileDescriptor
)
// Match Darwin and Linux behavior and throw
// .failedToChangeWorkingDirectory instead of .spawnFailed
if windowsError == ERROR_DIRECTORY {
throw SubprocessError.failedToChangeWorkingDirectory(
self.workingDirectory?.string,
underlyingError: SubprocessError.WindowsError(win32Error: windowsError)
)
}
throw SubprocessError.spawnFailed(
withUnderlyingError: SubprocessError.WindowsError(win32Error: windowsError)
)
}
do {
try Self.assignChildToJobObjectAndResume(
jobHandle: jobHandle,
processInfo: processInfo,
resumeThread: !userManagesResume
)
} catch {
try self.safelyCloseMultiple(
inputRead: inputReadFileDescriptor,
inputWrite: inputWriteFileDescriptor,
outputRead: outputReadFileDescriptor,
outputWrite: outputWriteFileDescriptor,
errorRead: errorReadFileDescriptor,
errorWrite: errorWriteFileDescriptor
)
throw error
}
// Transfer ownership of the job handle to the `ProcessIdentifier`.
jobHandleOwned = false
let pid = ProcessIdentifier(
value: processInfo.dwProcessId,
processDescriptor: processInfo.hProcess,
threadHandle: processInfo.hThread,
jobHandle: jobHandle
)
do {
// After spawn finishes, close all child side fds
try self.safelyCloseMultiple(
inputRead: inputReadFileDescriptor,
inputWrite: nil,
outputRead: nil,
outputWrite: outputWriteFileDescriptor,
errorRead: nil,
errorWrite: errorWriteFileDescriptor
)
} catch {
// If spawn() throws, monitorProcessTermination
// won't have an opportunity to call release, so do it here to avoid leaking the handles.
pid.close()
throw error
}
return SpawnResult(
processIdentifier: pid,
inputWriteEnd: inputWriteFileDescriptor,
outputReadEnd: outputReadFileDescriptor,
errorReadEnd: errorReadFileDescriptor
)
}
try self.safelyCloseMultiple(
inputRead: inputReadFileDescriptor,
inputWrite: inputWriteFileDescriptor,
outputRead: outputReadFileDescriptor,
outputWrite: outputWriteFileDescriptor,
errorRead: errorReadFileDescriptor,
errorWrite: errorWriteFileDescriptor
)
// If we reached this point, all possible executable paths have failed
throw SubprocessError.executableNotFound(
self.executable.description,
underlyingError: SubprocessError.WindowsError(win32Error: DWORD(ERROR_FILE_NOT_FOUND))
)
}
}
// MARK: - Platform Specific Options
/// The collection of platform-specific settings
/// to configure the subprocess when running.
public struct PlatformOptions: Sendable {
/// The credentials to use when spawning the subprocess
/// as a different user.
internal struct UserCredentials: Sendable, Hashable {
/// The name of the user.
///
/// This is the name of the user account to run as.
public var username: String
/// The clear-text password for the account.
public var password: String
/// The name of the domain or server whose account database
/// contains the account.
public var domain: String?
}
/// `ConsoleBehavior` describes how the console appears
/// when spawning a new process.
public struct ConsoleBehavior: Sendable, Hashable {
internal enum Storage: Sendable, Hashable {
case createNew
case detach
case inherit
}
internal let storage: Storage
private init(_ storage: Storage) {
self.storage = storage
}
/// The subprocess has a new console, instead of
/// inheriting its parent's console (the default).
public static let createNew: Self = .init(.createNew)
/// For console processes, the new process does not
/// inherit its parent's console (the default).
/// The new process can call the `AllocConsole`
/// function at a later time to create a console.
public static let detach: Self = .init(.detach)
/// The subprocess inherits its parent's console.
public static let inherit: Self = .init(.inherit)
}
/// `WindowStyle` describes how the window appears
/// when spawning a new process.
public struct WindowStyle: Sendable, Hashable {
internal enum Storage: Sendable, Hashable {
case normal
case hidden
case maximized
case minimized
}
internal let storage: Storage
internal var platformStyle: WORD {
switch self.storage {
case .hidden: return WORD(SW_HIDE)
case .maximized: return WORD(SW_SHOWMAXIMIZED)
case .minimized: return WORD(SW_SHOWMINIMIZED)
default: return WORD(SW_SHOWNORMAL)
}
}
private init(_ storage: Storage) {
self.storage = storage
}
/// Activates and displays a window of normal size.
public static let normal: Self = .init(.normal)
/// Doesn't activate a new window.
public static let hidden: Self = .init(.hidden)
/// Activates the window and displays it as a maximized window.
public static let maximized: Self = .init(.maximized)
/// Activates the window and displays it as a minimized window.
public static let minimized: Self = .init(.minimized)
}
/// The user credentials for starting the process as another user.
internal var userCredentials: UserCredentials? = nil
/// The console behavior of the new process.
///
/// Defaults to inheriting the console from the parent process.
public var consoleBehavior: ConsoleBehavior = .inherit
/// The window style to use when the process starts.
public var windowStyle: WindowStyle = .normal
/// A Boolean value that indicates whether to create a new process
/// group for the new process.
///
/// The process group includes all processes
/// that are descendants of this root process.
/// The process identifier of the new process group
/// is the same as the process identifier.
public var createProcessGroup: Bool = false
/// An ordered list of steps to tear down the child
/// process if the parent task is canceled before
/// the child process terminates.
///
/// The sequence always ends by forcefully terminating the process.
public var teardownSequence: [TeardownStep] = []
/// A closure that configures platform-specific
/// spawning constructs.
///
/// Use this closure to directly configure or override
/// the underlying platform-specific spawn settings that the
/// library uses internally, when higher-level APIs aren't
/// available for such modifications.
///
/// On Windows, Subprocess uses `CreateProcessW()` as the
/// underlying spawning mechanism. This closure allows
/// modification of the `dwCreationFlags` creation flag
/// and startup info `STARTUPINFOW` before
/// they are sent to `CreateProcessW()`.
///
/// - Important: Subprocess assigns every spawned child to
/// an internal Job Object before any user code runs in the child,
/// so teardown sequences targeting the process group can terminate
/// the child and all of its descendants together. To make this
/// assignment atomic, Subprocess always spawns children with
/// `CREATE_SUSPENDED` set in `dwCreationFlags`, regardless of the
/// value the configurator leaves in `dwCreationFlags`. By default,
/// Subprocess resumes the child after the assignment completes.
/// If the configurator sets `CREATE_SUSPENDED` in `dwCreationFlags`,
/// Subprocess treats this as a signal that user code will resume
/// the child explicitly, and therefore skips the internal `ResumeThread`
/// call. In that case the caller is responsible for calling
/// `ResumeThread` on the thread handle exposed through
/// `Execution.processIdentifier.threadHandle`. Otherwise, the child
/// will remain suspended indefinitely. If user code separately
/// assigns the child to its own Job Object after spawn, that
/// user-supplied job is nested inside Subprocess's job.
public var preSpawnProcessConfigurator:
(
@Sendable (
inout DWORD,
inout STARTUPINFOW
) throws(SubprocessError) -> Void
)? = nil
/// Creates platform options with default values.
public init() {}
}
extension PlatformOptions.ConsoleBehavior: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of how the console appears when spawning a
/// new process.
public var description: String {
switch self.storage {
case .createNew:
return "createNew"
case .detach:
return "detach"
case .inherit:
return "inherit"
}
}
/// A debug-oriented textual representation of how the console appears when
/// spawning a new process.
public var debugDescription: String {
return self.description
}
}
extension PlatformOptions.WindowStyle: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of how the window appears when spawning a
/// new process.
public var description: String {
switch self.storage {
case .normal:
return "normal"
case .hidden:
return "hidden"
case .maximized:
return "maximized"
case .minimized:
return "minimized"
}
}
/// A debug-oriented textual representation of how the window appears when
/// spawning a new process.
public var debugDescription: String {
return self.description
}
}
extension PlatformOptions: CustomStringConvertible, CustomDebugStringConvertible {
internal func description(withIndent indent: Int) -> String {
let indent = String(repeating: " ", count: indent * 4)
return """
PlatformOptions(
\(indent) userCredentials: \(String(describing: self.userCredentials)),
\(indent) consoleBehavior: \(self.consoleBehavior),
\(indent) windowStyle: \(self.windowStyle),
\(indent) createProcessGroup: \(self.createProcessGroup),
\(indent) preSpawnProcessConfigurator: \(self.preSpawnProcessConfigurator == nil ? "not set" : "set")
\(indent))
"""
}
/// A textual representation of the platform options.
public var description: String {
return self.description(withIndent: 0)
}
/// A debug-oriented textual representation of the platform options.
public var debugDescription: String {
return self.description(withIndent: 0)
}
}
// MARK: - Process Monitoring
@Sendable
internal func waitForProcessTermination(
for processIdentifier: ProcessIdentifier
) async throws(SubprocessError) {
// Once the continuation resumes, it will need to unregister the wait, so
// yield the wait handle back to the calling scope.
var waitHandle: HANDLE?
defer {
if let waitHandle {
_ = UnregisterWait(waitHandle)
}
}
try await _castError {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
// Set up a callback that immediately resumes the continuation and does no
// other work.
let context = Unmanaged.passRetained(continuation as AnyObject).toOpaque()
let callback: WAITORTIMERCALLBACK = { context, _ in
let continuation =
Unmanaged<AnyObject>.fromOpaque(context!).takeRetainedValue() as! CheckedContinuation<Void, any Error>
continuation.resume()
}
// We only want the callback to fire once (and not be rescheduled.) Waiting
// may take an arbitrarily long time, so let the thread pool know that too.
let flags = ULONG(WT_EXECUTEONLYONCE | WT_EXECUTELONGFUNCTION)
guard
RegisterWaitForSingleObject(
&waitHandle,
processIdentifier.processDescriptor,
callback,
context,
INFINITE,
flags
)
else {
let error: SubprocessError = .failedToMonitor(
withUnderlyingError: SubprocessError.WindowsError(win32Error: GetLastError())
)
continuation.resume(
throwing: error
)
return
}
}
}
}
@Sendable
internal func reapProcess(
with processIdentifier: ProcessIdentifier
) throws(SubprocessError) -> TerminationStatus {
// Windows keeps the exit code reachable through the process HANDLE
// until the HANDLE is closed, so there is no zombie to reap. We just
// need to read the exit code via `GetExitCodeProcess`.
var status: DWORD = 0
guard GetExitCodeProcess(processIdentifier.processDescriptor, &status) else {
throw SubprocessError.failedToMonitor(
withUnderlyingError: .init(win32Error: GetLastError())
)
}
return .exited(status)
}
// MARK: - Subprocess Control
extension Execution {
/// Terminate the current subprocess with the given exit code
/// - Parameters:
/// - exitCode: The exit code to use for the subprocess.
/// - toProcessGroup: When `true`, terminates the subprocess and any
/// descendants by terminating the Job Object that contains them. The
/// exit code is propagated to every process in the job. When `false`
/// (the default), terminates only the immediate child process, leaving
/// descendants unaffected.
public func terminate(
withExitCode exitCode: DWORD,
toProcessGroup: Bool = false
) throws(SubprocessError) {
if toProcessGroup {
guard TerminateJobObject(self.processIdentifier.jobHandle, exitCode) else {
throw SubprocessError.processControlFailed(
.terminate,
underlyingError: SubprocessError.WindowsError(win32Error: GetLastError())
)
}
} else {
guard TerminateProcess(self.processIdentifier.processDescriptor, exitCode) else {
throw SubprocessError.processControlFailed(
.terminate,
underlyingError: SubprocessError.WindowsError(win32Error: GetLastError())
)
}
}
}
/// Suspend the current subprocess
public func suspend() throws(SubprocessError) {
let NTSuspendProcess: (@convention(c) (HANDLE) -> LONG)? =
unsafeBitCast(
GetProcAddress(
GetModuleHandleA("ntdll.dll"),
"NtSuspendProcess"
),
to: Optional<(@convention(c) (HANDLE) -> LONG)>.self
)
guard let NTSuspendProcess = NTSuspendProcess else {
throw SubprocessError.processControlFailed(
.suspend,
underlyingError: SubprocessError.WindowsError(win32Error: GetLastError())
)
}
guard NTSuspendProcess(self.processIdentifier.processDescriptor) >= 0 else {
throw SubprocessError.processControlFailed(
.suspend,
underlyingError: SubprocessError.WindowsError(win32Error: GetLastError())
)
}
}
/// Resume the current subprocess after suspension
public func resume() throws(SubprocessError) {
let NTResumeProcess: (@convention(c) (HANDLE) -> LONG)? =
unsafeBitCast(
GetProcAddress(
GetModuleHandleA("ntdll.dll"),
"NtResumeProcess"
),
to: Optional<(@convention(c) (HANDLE) -> LONG)>.self
)
guard let NTResumeProcess = NTResumeProcess else {
throw SubprocessError.processControlFailed(
.resume,
underlyingError: SubprocessError.WindowsError(win32Error: GetLastError())
)
}
guard NTResumeProcess(self.processIdentifier.processDescriptor) >= 0 else {
throw SubprocessError.processControlFailed(
.resume,
underlyingError: SubprocessError.WindowsError(win32Error: GetLastError())
)
}
}
}
// MARK: - Executable Searching
extension Executable {
// Technically not needed for CreateProcess since
// it takes process name. It's here to support
// Executable.resolveExecutablePath
internal func resolveExecutablePath(withPathValue pathValue: String?) throws(SubprocessError) -> String {
switch self.storage {
case .executable(let executableName):
return try executableName._withCString(
encodedAs: UTF16.self
) { exeName throws(SubprocessError) -> String in
return try pathValue.withOptionalCString(
encodedAs: UTF16.self
) { path throws(SubprocessError) -> String in
let pathLength = SearchPathW(
path,
exeName,
nil,
0,
nil,
nil
)
guard pathLength > 0 else {
throw SubprocessError.executableNotFound(
executableName,
underlyingError: SubprocessError.WindowsError(win32Error: GetLastError())
)
}
return withUnsafeTemporaryAllocation(
of: WCHAR.self,
capacity: Int(pathLength) + 1
) {
_ = SearchPathW(
path,
exeName,
nil,
pathLength + 1,
$0.baseAddress,
nil
)
return String(decodingCString: $0.baseAddress!, as: UTF16.self)
}
}
}
case .path(let executablePath):
// Use path directly
return executablePath.string
}
}
/// `CreateProcessW` allows users to specify the executable path via
/// `lpApplicationName` or via `lpCommandLine`. However, only `lpCommandLine` supports
/// path searching, whereas `lpApplicationName` does not. In order to support the
/// "argument 0 override" feature, Subprocess must use `lpApplicationName` instead of
/// relying on `lpCommandLine` (so we can potentially set a different value for `lpCommandLine`).
///
/// This method replicates the executable searching behavior of `CreateProcessW`'s
/// `lpCommandLine`. Specifically, it follows the steps listed in `CreateProcessW`'s documentation:
///
/// 1. The directory from which the application loaded.
/// 2. The current directory for the parent process.
/// 3. The 32-bit Windows system directory.
/// 4. The 16-bit Windows system directory.
/// 5. The Windows directory.
/// 6. The directories that are listed in the PATH environment variable.
///
/// For more info:
/// https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw
internal func possibleExecutablePaths(
withPathValue pathValue: String?
) -> _OrderedSet<String> {
func insertExecutableAddingExtension(
_ name: String,
currentPath: String,
pathExtensions: _OrderedSet<String>,
storage: inout _OrderedSet<String>
) {
let fullPath = FilePath(currentPath).appending(name)
if !name.hasExtension() {
for ext in pathExtensions {
var path = fullPath
path.extension = ext
storage.insert(path.string)
}
} else {
storage.insert(fullPath.string)
}
}
switch self.storage {
case .executable(let name):
var possiblePaths: _OrderedSet<String> = .init()
let currentEnvironmentValues = Environment.currentEnvironmentValues()
// If `name` does not include extensions, we need to try these extensions
var pathExtensions: _OrderedSet<String> = _OrderedSet(["com", "exe", "bat", "cmd"])
if let extensionList = currentEnvironmentValues["PATHEXT"] {
for var ext in extensionList.split(separator: ";") {
ext.removeFirst(1)
pathExtensions.insert(String(ext).lowercased())
}
}
// 1. The directory from which the application loaded.
let applicationDirectory = try? fillNullTerminatedWideStringBuffer(
initialSize: DWORD(MAX_PATH), maxSize: DWORD(Int16.max)
) {
return GetModuleFileNameW(nil, $0.baseAddress, DWORD($0.count))
}
if let applicationDirectory {
insertExecutableAddingExtension(
name,
currentPath: FilePath(applicationDirectory).removingLastComponent().string,
pathExtensions: pathExtensions,
storage: &possiblePaths
)
}
// 2. Current directory
let directorySize = GetCurrentDirectoryW(0, nil)
let currentDirectory = try? fillNullTerminatedWideStringBuffer(
initialSize: directorySize,
maxSize: DWORD(Int16.max)
) {
return GetCurrentDirectoryW(DWORD($0.count), $0.baseAddress)
}
if let currentDirectory {
insertExecutableAddingExtension(
name,
currentPath: currentDirectory,
pathExtensions: pathExtensions,
storage: &possiblePaths
)
}
// 3. System directory (System32)
let systemDirectorySize = GetSystemDirectoryW(nil, 0)
let systemDirectory = try? fillNullTerminatedWideStringBuffer(
initialSize: systemDirectorySize,
maxSize: DWORD(Int16.max)
) {
return GetSystemDirectoryW($0.baseAddress, DWORD($0.count))
}
if let systemDirectory {
insertExecutableAddingExtension(
name,
currentPath: systemDirectory,
pathExtensions: pathExtensions,
storage: &possiblePaths
)
}
// 4. The Windows directory
let windowsDirectorySize = GetWindowsDirectoryW(nil, 0)
let windowsDirectory = try? fillNullTerminatedWideStringBuffer(
initialSize: windowsDirectorySize,
maxSize: DWORD(Int16.max)
) {
return GetWindowsDirectoryW($0.baseAddress, DWORD($0.count))
}
if let windowsDirectory {
insertExecutableAddingExtension(
name,
currentPath: windowsDirectory,
pathExtensions: pathExtensions,
storage: &possiblePaths
)
// 5. 16 bit Systen Directory
// Windows documentation stats that "No such standard function
// (similar to GetSystemDirectory) exists for the 16-bit system folder".
// Use "\(windowsDirectory)\System" instead
let systemDirectory16 = FilePath(windowsDirectory).appending("System")
insertExecutableAddingExtension(
name,
currentPath: systemDirectory16.string,
pathExtensions: pathExtensions,
storage: &possiblePaths
)
}
// 6. The directories that are listed in the PATH environment variable
if let pathValue {
let searchPaths = pathValue.split(separator: ";").map { String($0) }
for possiblePath in searchPaths {
insertExecutableAddingExtension(
name,
currentPath: possiblePath,
pathExtensions: pathExtensions,
storage: &possiblePaths
)
}
}
return possiblePaths
case .path(let path):
return _OrderedSet([path.string])
}
}
}
// MARK: - Environment Resolution
extension Environment {
internal func pathValue() -> String? {
switch self.config {
case .inherit(let overrides):
// If PATH value exists in overrides, use it
if let value = overrides[.path] {
return value
}
// Fall back to current process
return Self.currentEnvironmentValues()[.path]
case .custom(let fullEnvironment):
if let value = fullEnvironment[.path] {
return value
}
return nil
}
}
internal static func withCopiedEnv<R>(_ body: ([UnsafeMutablePointer<CChar>]) -> R) -> R {
var values: [UnsafeMutablePointer<CChar>] = []
guard let pwszEnvironmentBlock = GetEnvironmentStringsW() else {
return body([])
}
defer { FreeEnvironmentStringsW(pwszEnvironmentBlock) }
var pwszEnvironmentEntry: LPWCH? = pwszEnvironmentBlock
while let value = pwszEnvironmentEntry {
let entry = String(decodingCString: value, as: UTF16.self)
if entry.isEmpty { break }
values.append(entry.withCString { _strdup($0)! })
pwszEnvironmentEntry = pwszEnvironmentEntry?.advanced(by: wcslen(value) + 1)
}
defer { values.forEach { free($0) } }
return body(values)
}
}
// MARK: - ProcessIdentifier
/// A platform-independent identifier for a subprocess.
public struct ProcessIdentifier: Sendable, Hashable {
/// The Windows-specific process identifier value.
public let value: DWORD
/// The process handle for this execution.
public nonisolated(unsafe) let processDescriptor: HANDLE
/// The main thread handle for this execution.
public nonisolated(unsafe) let threadHandle: HANDLE
/// The Job Object handle that contains this process and any descendants.
internal nonisolated(unsafe) let jobHandle: HANDLE
internal init(
value: DWORD,
processDescriptor: HANDLE,
threadHandle: HANDLE,
jobHandle: HANDLE
) {
self.value = value
self.processDescriptor = processDescriptor
self.threadHandle = threadHandle
self.jobHandle = jobHandle
}
internal func close() {
guard CloseHandle(self.threadHandle) else {
fatalError("Failed to close thread HANDLE: \(SubprocessError.WindowsError(win32Error: GetLastError()))")
}
guard CloseHandle(self.processDescriptor) else {
fatalError("Failed to close process HANDLE: \(SubprocessError.WindowsError(win32Error: GetLastError()))")
}
guard CloseHandle(self.jobHandle) else {
fatalError("Failed to close job HANDLE: \(SubprocessError.WindowsError(win32Error: GetLastError()))")
}
}
}
extension ProcessIdentifier: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of the process identifier.
public var description: String {
return "(processID: \(self.value))"
}
/// A debug-oriented textual representation of the process identifier.
public var debugDescription: String {
return description
}
}
// MARK: - Private Utils
extension Configuration {
private func preSpawn(withPossibleExecutablePath executablePath: String) throws(SubprocessError) -> (
applicationName: String?,
commandAndArgs: String,
environment: String,
intendedWorkingDir: String?
) {
// Prepare environment
var env: [Environment.Key: String] = [:]
switch self.environment.config {
case .custom(let customValues):
// Use the custom values directly
env = customValues
case .inherit(let updateValues):
// Combine current environment
env = Environment.currentEnvironmentValues()
for (key, value) in updateValues {
if let value {
// Update env with ew value
env.updateValue(value, forKey: key)
} else {
// If `value` is `nil`, unset this value from env
env.removeValue(forKey: key)
}
}
}
// On Windows, the PATH is required in order to locate dlls needed by
// the process so we should also pass that to the child
if env[.path] == nil,
let parentPath = Environment.currentEnvironmentValues()[.path]
{
env[.path] = parentPath
}
// The environment string must be terminated by a double
// null-terminator. Otherwise, CreateProcess will fail with
// INVALID_PARMETER.
let environmentString =
env.map {
$0.key.rawValue + "=" + $0.value
}.joined(separator: "\0") + "\0\0"
// Prepare arguments
let (
applicationName,
commandAndArgs