forked from swiftlang/swift-corelibs-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProcess.swift
981 lines (808 loc) · 36.8 KB
/
Process.swift
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
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016, 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if !os(Android) // not available
import CoreFoundation
extension Process {
public enum TerminationReason : Int {
case exit
case uncaughtSignal
}
}
private func WIFEXITED(_ status: Int32) -> Bool {
return _WSTATUS(status) == 0
}
private func _WSTATUS(_ status: Int32) -> Int32 {
return status & 0x7f
}
private func WIFSIGNALED(_ status: Int32) -> Bool {
return (_WSTATUS(status) != 0) && (_WSTATUS(status) != 0x7f)
}
private func WEXITSTATUS(_ status: Int32) -> Int32 {
return (status >> 8) & 0xff
}
private func WTERMSIG(_ status: Int32) -> Int32 {
return status & 0x7f
}
private var managerThreadRunLoop : RunLoop? = nil
private var managerThreadRunLoopIsRunning = false
private var managerThreadRunLoopIsRunningCondition = NSCondition()
#if os(macOS) || os(iOS)
internal let kCFSocketDataCallBack = CFSocketCallBackType.dataCallBack.rawValue
#endif
private func emptyRunLoopCallback(_ context : UnsafeMutableRawPointer?) -> Void {}
// Retain method for run loop source
private func runLoopSourceRetain(_ pointer : UnsafeRawPointer?) -> UnsafeRawPointer? {
let ref = Unmanaged<AnyObject>.fromOpaque(pointer!).takeUnretainedValue()
let retained = Unmanaged<AnyObject>.passRetained(ref)
return unsafeBitCast(retained, to: UnsafeRawPointer.self)
}
// Release method for run loop source
private func runLoopSourceRelease(_ pointer : UnsafeRawPointer?) -> Void {
Unmanaged<AnyObject>.fromOpaque(pointer!).release()
}
// Equal method for run loop source
private func runloopIsEqual(_ a : UnsafeRawPointer?, _ b : UnsafeRawPointer?) -> _DarwinCompatibleBoolean {
let unmanagedrunLoopA = Unmanaged<AnyObject>.fromOpaque(a!)
guard let runLoopA = unmanagedrunLoopA.takeUnretainedValue() as? RunLoop else {
return false
}
let unmanagedRunLoopB = Unmanaged<AnyObject>.fromOpaque(a!)
guard let runLoopB = unmanagedRunLoopB.takeUnretainedValue() as? RunLoop else {
return false
}
guard runLoopA == runLoopB else {
return false
}
return true
}
// Equal method for process in run loop source
private func processIsEqual(_ a : UnsafeRawPointer?, _ b : UnsafeRawPointer?) -> _DarwinCompatibleBoolean {
let unmanagedProcessA = Unmanaged<AnyObject>.fromOpaque(a!)
guard let processA = unmanagedProcessA.takeUnretainedValue() as? Process else {
return false
}
let unmanagedProcessB = Unmanaged<AnyObject>.fromOpaque(a!)
guard let processB = unmanagedProcessB.takeUnretainedValue() as? Process else {
return false
}
guard processA == processB else {
return false
}
return true
}
#if os(Windows)
private func quoteWindowsCommandLine(_ commandLine: [String]) -> String {
func quoteWindowsCommandArg(arg: String) -> String {
// Windows escaping, adapted from Daniel Colascione's "Everyone quotes
// command line arguments the wrong way" - Microsoft Developer Blog
if !arg.contains(where: {" \t\n\"".contains($0)}) {
return arg
}
// To escape the command line, we surround the argument with quotes. However
// the complication comes due to how the Windows command line parser treats
// backslashes (\) and quotes (")
//
// - \ is normally treated as a literal backslash
// - e.g. foo\bar\baz => foo\bar\baz
// - However, the sequence \" is treated as a literal "
// - e.g. foo\"bar => foo"bar
//
// But then what if we are given a path that ends with a \? Surrounding
// foo\bar\ with " would be "foo\bar\" which would be an unterminated string
// since it ends on a literal quote. To allow this case the parser treats:
//
// - \\" as \ followed by the " metachar
// - \\\" as \ followed by a literal "
// - In general:
// - 2n \ followed by " => n \ followed by the " metachar
// - 2n+1 \ followed by " => n \ followed by a literal "
var quoted = "\""
var unquoted = arg.unicodeScalars
while !unquoted.isEmpty {
guard let firstNonBackslash = unquoted.firstIndex(where: { $0 != "\\" }) else {
// String ends with a backslash e.g. foo\bar\, escape all the backslashes
// then add the metachar " below
let backslashCount = unquoted.count
quoted.append(String(repeating: "\\", count: backslashCount * 2))
break
}
let backslashCount = unquoted.distance(from: unquoted.startIndex, to: firstNonBackslash)
if (unquoted[firstNonBackslash] == "\"") {
// This is a string of \ followed by a " e.g. foo\"bar. Escape the
// backslashes and the quote
quoted.append(String(repeating: "\\", count: backslashCount * 2 + 1))
quoted.append(String(unquoted[firstNonBackslash]))
} else {
// These are just literal backslashes
quoted.append(String(repeating: "\\", count: backslashCount))
quoted.append(String(unquoted[firstNonBackslash]))
}
// Drop the backslashes and the following character
unquoted.removeFirst(backslashCount + 1)
}
quoted.append("\"")
return quoted
}
return commandLine.map(quoteWindowsCommandArg).joined(separator: " ")
}
#endif
open class Process: NSObject {
private static func setup() {
struct Once {
static var done = false
static let lock = NSLock()
}
Once.lock.synchronized {
if !Once.done {
let thread = Thread {
managerThreadRunLoop = RunLoop.current
var emptySourceContext = CFRunLoopSourceContext()
emptySourceContext.version = 0
emptySourceContext.retain = runLoopSourceRetain
emptySourceContext.release = runLoopSourceRelease
emptySourceContext.equal = runloopIsEqual
emptySourceContext.perform = emptyRunLoopCallback
managerThreadRunLoop!.withUnretainedReference {
(refPtr: UnsafeMutablePointer<UInt8>) in
emptySourceContext.info = UnsafeMutableRawPointer(refPtr)
}
CFRunLoopAddSource(managerThreadRunLoop?._cfRunLoop, CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &emptySourceContext), kCFRunLoopDefaultMode)
managerThreadRunLoopIsRunningCondition.lock()
CFRunLoopPerformBlock(managerThreadRunLoop?._cfRunLoop, kCFRunLoopDefaultMode) {
managerThreadRunLoopIsRunning = true
managerThreadRunLoopIsRunningCondition.broadcast()
managerThreadRunLoopIsRunningCondition.unlock()
}
managerThreadRunLoop?.run()
fatalError("Process manager run loop exited unexpectedly; it should run forever once initialized")
}
thread.start()
managerThreadRunLoopIsRunningCondition.lock()
while managerThreadRunLoopIsRunning == false {
managerThreadRunLoopIsRunningCondition.wait()
}
managerThreadRunLoopIsRunningCondition.unlock()
Once.done = true
}
}
}
// Create an Process which can be run at a later time
// An Process can only be run once. Subsequent attempts to
// run an Process will raise.
// Upon process death a notification will be sent
// { Name = ProcessDidTerminateNotification; object = process; }
//
public override init() {
}
// These properties can only be set before a launch.
open var executableURL: URL?
open var currentDirectoryURL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath, isDirectory: true)
open var arguments: [String]?
open var environment: [String : String]? // if not set, use current
@available(*, deprecated, renamed: "executableURL")
open var launchPath: String? {
get { return executableURL?.path }
set { executableURL = (newValue != nil) ? URL(fileURLWithPath: newValue!) : nil }
}
@available(*, deprecated, renamed: "currentDirectoryURL")
open var currentDirectoryPath: String {
get { return currentDirectoryURL.path }
set { currentDirectoryURL = URL(fileURLWithPath: newValue) }
}
// Standard I/O channels; could be either a FileHandle or a Pipe
open var standardInput: Any? = FileHandle._stdinFileHandle {
willSet {
precondition(newValue is Pipe || newValue is FileHandle || newValue == nil,
"standardInput must be either Pipe or FileHandle")
}
}
open var standardOutput: Any? = FileHandle._stdoutFileHandle {
willSet {
precondition(newValue is Pipe || newValue is FileHandle || newValue == nil,
"standardOutput must be either Pipe or FileHandle")
}
}
open var standardError: Any? = FileHandle._stderrFileHandle {
willSet {
precondition(newValue is Pipe || newValue is FileHandle || newValue == nil,
"standardError must be either Pipe or FileHandle")
}
}
private var runLoopSourceContext : CFRunLoopSourceContext?
private var runLoopSource : CFRunLoopSource?
fileprivate weak var runLoop : RunLoop? = nil
private var processLaunchedCondition = NSCondition()
// Actions
@available(*, deprecated, renamed: "run")
open func launch() {
do {
try run()
} catch let nserror as NSError {
if let path = nserror.userInfo[NSFilePathErrorKey] as? String, path == currentDirectoryPath {
// Foundation throws an NSException when changing the working directory fails,
// and unfortunately launch() is not marked `throws`, so we get away with a
// fatalError.
switch CocoaError.Code(rawValue: nserror.code) {
case .fileReadNoSuchFile:
fatalError("Process: The specified working directory does not exist.")
case .fileReadNoPermission:
fatalError("Process: The specified working directory cannot be accessed.")
default:
fatalError("Process: The specified working directory cannot be set.")
}
}
} catch {
fatalError(String(describing: error))
}
}
#if os(Windows)
private func _socketpair() -> (first: SOCKET, second: SOCKET) {
let listener: SOCKET = socket(AF_INET, SOCK_STREAM, 0)
if listener == INVALID_SOCKET {
return (first: INVALID_SOCKET, second: INVALID_SOCKET)
}
defer { closesocket(listener) }
var result: Int32 = SOCKET_ERROR
var address: sockaddr_in =
sockaddr_in(sin_family: ADDRESS_FAMILY(AF_INET), sin_port: USHORT(0),
sin_addr: IN_ADDR(S_un: in_addr.__Unnamed_union_S_un(S_un_b: in_addr.__Unnamed_union_S_un.__Unnamed_struct_S_un_b(s_b1: 127, s_b2: 0, s_b3: 0, s_b4: 1))),
sin_zero: (CHAR(0), CHAR(0), CHAR(0), CHAR(0), CHAR(0), CHAR(0), CHAR(0), CHAR(0)))
withUnsafePointer(to: &address) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
result = bind(listener, $0, Int32(MemoryLayout<sockaddr_in>.size))
}
}
if result == SOCKET_ERROR {
return (first: INVALID_SOCKET, second: INVALID_SOCKET)
}
if listen(listener, 1) == SOCKET_ERROR {
return (first: INVALID_SOCKET, second: INVALID_SOCKET)
}
withUnsafeMutablePointer(to: &address) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
var value: Int32 = Int32(MemoryLayout<sockaddr_in>.size)
result = getsockname(listener, $0, &value)
}
}
if result == SOCKET_ERROR {
return (first: INVALID_SOCKET, second: INVALID_SOCKET)
}
let first: SOCKET = socket(AF_INET, SOCK_STREAM, 0)
if first == INVALID_SOCKET {
return (first: INVALID_SOCKET, second: INVALID_SOCKET)
}
withUnsafePointer(to: &address) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
result = connect(first, $0, Int32(MemoryLayout<sockaddr_in>.size))
}
}
if result == SOCKET_ERROR {
closesocket(first)
return (first: INVALID_SOCKET, second: INVALID_SOCKET)
}
var value: u_long = 1
if ioctlsocket(first, FIONBIO, &value) == SOCKET_ERROR {
closesocket(first)
return (first: INVALID_SOCKET, second: INVALID_SOCKET)
}
let second: SOCKET = accept(listener, nil, nil)
if second == INVALID_SOCKET {
closesocket(first)
return (first: INVALID_SOCKET, second: INVALID_SOCKET)
}
return (first: first, second: second)
}
#endif
open func run() throws {
self.processLaunchedCondition.lock()
defer {
self.processLaunchedCondition.broadcast()
self.processLaunchedCondition.unlock()
}
// Dispatch the manager thread if it isn't already running
Process.setup()
// Ensure that the launch path is set
guard let launchPath = self.executableURL?.path else {
throw NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError)
}
#if os(Windows)
var command: [String] = [launchPath]
if let arguments = self.arguments {
command.append(contentsOf: arguments)
}
var siStartupInfo: STARTUPINFOW = STARTUPINFOW()
siStartupInfo.cb = DWORD(MemoryLayout<STARTUPINFOW>.size)
var _devNull: FileHandle?
func devNullFd() throws -> HANDLE {
_devNull = try _devNull ?? FileHandle(forUpdating: URL(fileURLWithPath: "NUL", isDirectory: false))
return _devNull!.handle
}
switch standardInput {
case let pipe as Pipe:
siStartupInfo.hStdInput = pipe.fileHandleForReading.handle
// nil or NullDevice maps to NUL
case let handle as FileHandle where handle === FileHandle._nulldeviceFileHandle: fallthrough
case .none:
siStartupInfo.hStdInput = try devNullFd()
case let handle as FileHandle:
siStartupInfo.hStdInput = handle.handle
default: break
}
switch standardOutput {
case let pipe as Pipe:
siStartupInfo.hStdOutput = pipe.fileHandleForWriting.handle
// nil or NullDevice maps to NUL
case let handle as FileHandle where handle === FileHandle._nulldeviceFileHandle: fallthrough
case .none:
siStartupInfo.hStdOutput = try devNullFd()
case let handle as FileHandle:
siStartupInfo.hStdOutput = handle.handle
default: break
}
switch standardError {
case let pipe as Pipe:
siStartupInfo.hStdError = pipe.fileHandleForWriting.handle
// nil or NullDevice maps to NUL
case let handle as FileHandle where handle === FileHandle._nulldeviceFileHandle: fallthrough
case .none:
siStartupInfo.hStdError = try devNullFd()
case let handle as FileHandle:
siStartupInfo.hStdError = handle.handle
default: break
}
var piProcessInfo: PROCESS_INFORMATION = PROCESS_INFORMATION()
var environment: [String:String] = [:]
if let env = self.environment {
environment = env
} else {
environment = ProcessInfo.processInfo.environment
environment["PWD"] = currentDirectoryURL.path
}
// NOTE(compnerd) the environment string must be terminated by a double
// null-terminator. Otherwise, CreateProcess will fail with
// INVALID_PARMETER.
let szEnvironment: String = environment.map { $0.key + "=" + $0.value }.joined(separator: "\0") + "\0\0"
let sockets: (first: SOCKET, second: SOCKET) = _socketpair()
var context: CFSocketContext = CFSocketContext()
context.version = 0
context.retain = runLoopSourceRetain
context.release = runLoopSourceRelease
context.info = Unmanaged.passUnretained(self).toOpaque()
let socket: CFSocket =
CFSocketCreateWithNative(nil, CFSocketNativeHandle(sockets.first), CFOptionFlags(kCFSocketDataCallBack), { (socket, type, address, data, info) in
let process: Process = NSObject.unretainedReference(info!)
process.processLaunchedCondition.lock()
while process.isRunning == false {
process.processLaunchedCondition.wait()
}
process.processLaunchedCondition.unlock()
WaitForSingleObject(process.processHandle, WinSDK.INFINITE)
var dwExitCode: DWORD = 0
// FIXME(compnerd) how do we handle errors here?
GetExitCodeProcess(process.processHandle, &dwExitCode)
// TODO(compnerd) check if the process terminated abnormally
process._terminationStatus = Int32(dwExitCode)
process._terminationReason = .exit
if let handler = process.terminationHandler {
let thread: Thread = Thread { handler(process) }
thread.start()
}
process.isRunning = false
// Invalidate the source and wake up the run loop, if it is available
CFRunLoopSourceInvalidate(process.runLoopSource)
if let runloop = process.runLoop {
CFRunLoopWakeUp(runloop._cfRunLoop)
}
CFSocketInvalidate(socket)
}, &context)
CFSocketSetSocketFlags(socket, CFOptionFlags(kCFSocketCloseOnInvalidate))
let source: CFRunLoopSource =
CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0)
CFRunLoopAddSource(managerThreadRunLoop?._cfRunLoop, source, kCFRunLoopDefaultMode)
try quoteWindowsCommandLine(command).withCString(encodedAs: UTF16.self) { wszCommandLine in
try currentDirectoryURL.path.withCString(encodedAs: UTF16.self) { wszCurrentDirectory in
try szEnvironment.withCString(encodedAs: UTF16.self) { wszEnvironment in
if !CreateProcessW(nil, UnsafeMutablePointer<WCHAR>(mutating: wszCommandLine),
nil, nil, true,
DWORD(CREATE_UNICODE_ENVIRONMENT), UnsafeMutableRawPointer(mutating: wszEnvironment),
wszCurrentDirectory,
&siStartupInfo, &piProcessInfo) {
throw _NSErrorWithWindowsError(GetLastError(), reading: false)
}
}
}
}
self.processHandle = piProcessInfo.hProcess
if !CloseHandle(piProcessInfo.hThread) {
throw _NSErrorWithWindowsError(GetLastError(), reading: false)
}
if let pipe = standardInput as? Pipe {
pipe.fileHandleForReading.closeFile()
}
if let pipe = standardOutput as? Pipe {
pipe.fileHandleForWriting.closeFile()
}
if let pipe = standardError as? Pipe {
pipe.fileHandleForWriting.closeFile()
}
self.runLoop = RunLoop.current
self.runLoopSourceContext =
CFRunLoopSourceContext(version: 0,
info: Unmanaged.passUnretained(self).toOpaque(),
retain: { runLoopSourceRetain($0) },
release: { runLoopSourceRelease($0) },
copyDescription: nil,
equal: { processIsEqual($0, $1) },
hash: nil,
schedule: nil,
cancel: nil,
perform: { emptyRunLoopCallback($0) })
self.runLoopSource = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &self.runLoopSourceContext!)
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode)
isRunning = true
closesocket(sockets.second)
#else
// Initial checks that the launchPath points to an executable file. posix_spawn()
// can return success even if executing the program fails, eg fork() works but execve()
// fails, so try and check as much as possible beforehand.
try FileManager.default._fileSystemRepresentation(withPath: launchPath, { fsRep in
var statInfo = stat()
guard stat(fsRep, &statInfo) == 0 else {
throw _NSErrorWithErrno(errno, reading: true, path: launchPath)
}
let isRegularFile: Bool = statInfo.st_mode & S_IFMT == S_IFREG
guard isRegularFile == true else {
throw NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError)
}
guard access(fsRep, X_OK) == 0 else {
throw _NSErrorWithErrno(errno, reading: true, path: launchPath)
}
})
// Convert the arguments array into a posix_spawn-friendly format
var args = [launchPath]
if let arguments = self.arguments {
args.append(contentsOf: arguments)
}
let argv : UnsafeMutablePointer<UnsafeMutablePointer<Int8>?> = args.withUnsafeBufferPointer {
let array : UnsafeBufferPointer<String> = $0
let buffer = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: array.count + 1)
buffer.initialize(from: array.map { $0.withCString(strdup) }, count: array.count)
buffer[array.count] = nil
return buffer
}
defer {
for arg in argv ..< argv + args.count {
free(UnsafeMutableRawPointer(arg.pointee))
}
argv.deallocate()
}
var env: [String: String]
if let e = environment {
env = e
} else {
env = ProcessInfo.processInfo.environment
env["PWD"] = currentDirectoryURL.path
}
let nenv = env.count
let envp = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: 1 + nenv)
envp.initialize(from: env.map { strdup("\($0)=\($1)") }, count: nenv)
envp[env.count] = nil
defer {
for pair in envp ..< envp + env.count {
free(UnsafeMutableRawPointer(pair.pointee))
}
envp.deallocate()
}
var taskSocketPair : [Int32] = [0, 0]
#if os(macOS) || os(iOS)
socketpair(AF_UNIX, SOCK_STREAM, 0, &taskSocketPair)
#else
socketpair(AF_UNIX, Int32(SOCK_STREAM.rawValue), 0, &taskSocketPair)
#endif
var context = CFSocketContext()
context.version = 0
context.retain = runLoopSourceRetain
context.release = runLoopSourceRelease
context.info = Unmanaged.passUnretained(self).toOpaque()
let socket = CFSocketCreateWithNative( nil, taskSocketPair[0], CFOptionFlags(kCFSocketDataCallBack), {
(socket, type, address, data, info ) in
let process: Process = NSObject.unretainedReference(info!)
process.processLaunchedCondition.lock()
while process.isRunning == false {
process.processLaunchedCondition.wait()
}
process.processLaunchedCondition.unlock()
var exitCode : Int32 = 0
#if CYGWIN
let exitCodePtrWrapper = withUnsafeMutablePointer(to: &exitCode) {
exitCodePtr in
__wait_status_ptr_t(__int_ptr: exitCodePtr)
}
#endif
var waitResult : Int32 = 0
repeat {
#if CYGWIN
waitResult = waitpid( process.processIdentifier, exitCodePtrWrapper, 0)
#else
waitResult = waitpid( process.processIdentifier, &exitCode, 0)
#endif
} while ( (waitResult == -1) && (errno == EINTR) )
if WIFSIGNALED(exitCode) {
process._terminationStatus = WTERMSIG(exitCode)
process._terminationReason = .uncaughtSignal
} else {
assert(WIFEXITED(exitCode))
process._terminationStatus = WEXITSTATUS(exitCode)
process._terminationReason = .exit
}
// If a termination handler has been set, invoke it on a background thread
if let terminationHandler = process.terminationHandler {
let thread = Thread {
terminationHandler(process)
}
thread.start()
}
// Set the running flag to false
process.isRunning = false
// Invalidate the source and wake up the run loop, if it's available
CFRunLoopSourceInvalidate(process.runLoopSource)
if let runLoop = process.runLoop {
CFRunLoopWakeUp(runLoop._cfRunLoop)
}
CFSocketInvalidate( socket )
}, &context )
CFSocketSetSocketFlags( socket, CFOptionFlags(kCFSocketCloseOnInvalidate))
let source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0)
CFRunLoopAddSource(managerThreadRunLoop?._cfRunLoop, source, kCFRunLoopDefaultMode)
// file_actions
#if os(macOS) || os(iOS) || CYGWIN
var fileActions: posix_spawn_file_actions_t? = nil
#else
var fileActions: posix_spawn_file_actions_t = posix_spawn_file_actions_t()
#endif
posix(posix_spawn_file_actions_init(&fileActions))
defer { posix_spawn_file_actions_destroy(&fileActions) }
// File descriptors to duplicate in the child process. This allows
// output redirection to NSPipe or NSFileHandle.
var adddup2 = [Int32: Int32]()
// File descriptors to close in the child process. A set so that
// shared pipes only get closed once. Would result in EBADF on OSX
// otherwise.
var addclose = Set<Int32>()
var _devNull: FileHandle?
func devNullFd() throws -> Int32 {
_devNull = try _devNull ?? FileHandle(forUpdating: URL(fileURLWithPath: "/dev/null", isDirectory: false))
return _devNull!.fileDescriptor
}
switch standardInput {
case let pipe as Pipe:
adddup2[STDIN_FILENO] = pipe.fileHandleForReading.fileDescriptor
addclose.insert(pipe.fileHandleForWriting.fileDescriptor)
// nil or NullDevice map to /dev/null
case let handle as FileHandle where handle === FileHandle._nulldeviceFileHandle: fallthrough
case .none:
adddup2[STDIN_FILENO] = try devNullFd()
// No need to dup stdin to stdin
case let handle as FileHandle where handle === FileHandle._stdinFileHandle: break
case let handle as FileHandle:
adddup2[STDIN_FILENO] = handle.fileDescriptor
default: break
}
switch standardOutput {
case let pipe as Pipe:
adddup2[STDOUT_FILENO] = pipe.fileHandleForWriting.fileDescriptor
addclose.insert(pipe.fileHandleForReading.fileDescriptor)
// nil or NullDevice map to /dev/null
case let handle as FileHandle where handle === FileHandle._nulldeviceFileHandle: fallthrough
case .none:
adddup2[STDIN_FILENO] = try devNullFd()
// No need to dup stdout to stdout
case let handle as FileHandle where handle === FileHandle._stdoutFileHandle: break
case let handle as FileHandle:
adddup2[STDOUT_FILENO] = handle.fileDescriptor
default: break
}
switch standardError {
case let pipe as Pipe:
adddup2[STDERR_FILENO] = pipe.fileHandleForWriting.fileDescriptor
addclose.insert(pipe.fileHandleForReading.fileDescriptor)
// nil or NullDevice map to /dev/null
case let handle as FileHandle where handle === FileHandle._nulldeviceFileHandle: fallthrough
case .none:
adddup2[STDIN_FILENO] = try devNullFd()
// No need to dup stderr to stderr
case let handle as FileHandle where handle === FileHandle._stderrFileHandle: break
case let handle as FileHandle:
adddup2[STDERR_FILENO] = handle.fileDescriptor
default: break
}
for (new, old) in adddup2 {
posix(posix_spawn_file_actions_adddup2(&fileActions, old, new))
}
for fd in addclose {
posix(posix_spawn_file_actions_addclose(&fileActions, fd))
}
let fileManager = FileManager()
let previousDirectoryPath = fileManager.currentDirectoryPath
if !fileManager.changeCurrentDirectoryPath(currentDirectoryURL.path) {
throw _NSErrorWithErrno(errno, reading: true, url: currentDirectoryURL)
}
defer {
// Reset the previous working directory path.
fileManager.changeCurrentDirectoryPath(previousDirectoryPath)
}
// Launch
var pid = pid_t()
guard posix_spawn(&pid, launchPath, &fileActions, nil, argv, envp) == 0 else {
throw _NSErrorWithErrno(errno, reading: true, path: launchPath)
}
// Close the write end of the input and output pipes.
if let pipe = standardInput as? Pipe {
pipe.fileHandleForReading.closeFile()
}
if let pipe = standardOutput as? Pipe {
pipe.fileHandleForWriting.closeFile()
}
if let pipe = standardError as? Pipe {
pipe.fileHandleForWriting.closeFile()
}
close(taskSocketPair[1])
self.runLoop = RunLoop.current
self.runLoopSourceContext = CFRunLoopSourceContext(version: 0,
info: Unmanaged.passUnretained(self).toOpaque(),
retain: { return runLoopSourceRetain($0) },
release: { runLoopSourceRelease($0) },
copyDescription: nil,
equal: { return processIsEqual($0, $1) },
hash: nil,
schedule: nil,
cancel: nil,
perform: { emptyRunLoopCallback($0) })
self.runLoopSource = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &runLoopSourceContext!)
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode)
isRunning = true
self.processIdentifier = pid
#endif
}
open func interrupt() {
precondition(hasStarted, "task not launched")
#if os(Windows)
TerminateProcess(processHandle, UINT(SIGINT))
#else
kill(processIdentifier, SIGINT)
#endif
}
open func terminate() {
precondition(hasStarted, "task not launched")
#if os(Windows)
TerminateProcess(processHandle, UINT(SIGTERM))
#else
kill(processIdentifier, SIGTERM)
#endif
}
// Every suspend() has to be balanced with a resume() so keep a count of both.
private var suspendCount = 0
open func suspend() -> Bool {
#if os(Windows)
let pNTSuspendProcess: Optional<(HANDLE) -> LONG> =
unsafeBitCast(GetProcAddress(GetModuleHandleA("ntdll.dll"),
"NtSuspendProcess"),
to: Optional<(HANDLE) -> LONG>.self)
if let pNTSuspendProcess = pNTSuspendProcess {
if pNTSuspendProcess(processHandle) < 0 {
return false
}
suspendCount += 1
return true
}
return false
#else
if kill(processIdentifier, SIGSTOP) == 0 {
suspendCount += 1
return true
} else {
return false
}
#endif
}
open func resume() -> Bool {
var success: Bool = true
#if os(Windows)
if suspendCount == 1 {
let pNTResumeProcess: Optional<(HANDLE) -> NTSTATUS> =
unsafeBitCast(GetProcAddress(GetModuleHandleA("ntdll.dll"),
"NtResumeProcess"),
to: Optional<(HANDLE) -> NTSTATUS>.self)
if let pNTResumeProcess = pNTResumeProcess {
if pNTResumeProcess(processHandle) < 0 {
success = false
}
}
}
#else
if suspendCount == 1 {
success = kill(processIdentifier, SIGCONT) == 0
}
#endif
if success {
suspendCount -= 1
}
return success
}
// status
#if os(Windows)
open private(set) var processHandle: HANDLE = INVALID_HANDLE_VALUE
open var processIdentifier: Int32 {
return Int32(GetProcessId(processHandle))
}
open private(set) var isRunning: Bool = false
private var hasStarted: Bool {
return processHandle != INVALID_HANDLE_VALUE
}
private var hasFinished: Bool {
return hasStarted && !isRunning
}
#else
open private(set) var processIdentifier: Int32 = 0
open private(set) var isRunning: Bool = false
private var hasStarted: Bool { return processIdentifier > 0 }
private var hasFinished: Bool { return !isRunning && processIdentifier > 0 }
#endif
private var _terminationStatus: Int32 = 0
public var terminationStatus: Int32 {
precondition(hasStarted, "task not launched")
precondition(hasFinished, "task still running")
return _terminationStatus
}
private var _terminationReason: TerminationReason = .exit
public var terminationReason: TerminationReason {
precondition(hasStarted, "task not launched")
precondition(hasFinished, "task still running")
return _terminationReason
}
/*
A block to be invoked when the process underlying the Process terminates. Setting the block to nil is valid, and stops the previous block from being invoked, as long as it hasn't started in any way. The Process is passed as the argument to the block so the block does not have to capture, and thus retain, it. The block is copied when set. Only one termination handler block can be set at any time. The execution context in which the block is invoked is undefined. If the Process has already finished, the block is executed immediately/soon (not necessarily on the current thread). If a terminationHandler is set on an Process, the ProcessDidTerminateNotification notification is not posted for that process. Also note that -waitUntilExit won't wait until the terminationHandler has been fully executed. You cannot use this property in a concrete subclass of Process which hasn't been updated to include an implementation of the storage and use of it.
*/
open var terminationHandler: ((Process) -> Void)?
open var qualityOfService: QualityOfService = .default // read-only after the process is launched
open class func run(_ url: URL, arguments: [String], terminationHandler: ((Process) -> Void)? = nil) throws -> Process {
let process = Process()
process.executableURL = url
process.arguments = arguments
process.terminationHandler = terminationHandler
try process.run()
return process
}
@available(*, deprecated, renamed: "run(_:arguments:terminationHandler:)")
// convenience; create and launch
open class func launchedProcess(launchPath path: String, arguments: [String]) -> Process {
let process = Process()
process.launchPath = path
process.arguments = arguments
process.launch()
return process
}
// poll the runLoop in defaultMode until process completes
open func waitUntilExit() {
repeat {
} while( self.isRunning == true && RunLoop.current.run(mode: .default, before: Date(timeIntervalSinceNow: 0.05)) )
self.runLoop = nil
}
}
extension Process {
public static let didTerminateNotification = NSNotification.Name(rawValue: "NSTaskDidTerminateNotification")
}
private func posix(_ code: Int32) {
switch code {
case 0: return
case EBADF: fatalError("POSIX command failed with error: \(code) -- EBADF")
default: fatalError("POSIX command failed with error: \(code)")
}
}
#endif