Skip to content

Commit 596e6ed

Browse files
committed
SR-11699: Process: Closing standardInput before calling run() aborts with EBADF
- Check the file descriptor passed to _CFPosixSpawnFileActionsAddClose() is valid.
1 parent facf571 commit 596e6ed

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

Foundation/Process.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -860,7 +860,7 @@ open class Process: NSObject {
860860
for (new, old) in adddup2 {
861861
posix(_CFPosixSpawnFileActionsAddDup2(fileActions, old, new))
862862
}
863-
for fd in addclose {
863+
for fd in addclose.filter({ $0 >= 0 }) {
864864
posix(_CFPosixSpawnFileActionsAddClose(fileActions, fd))
865865
}
866866

TestFoundation/TestProcess.swift

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -696,6 +696,33 @@ class TestProcess : XCTestCase {
696696
}
697697
}
698698

699+
func test_pipeCloseBeforeLaunch() {
700+
let process = Process()
701+
let stdInput = Pipe()
702+
let stdOutput = Pipe()
703+
704+
process.executableURL = xdgTestHelperURL()
705+
process.arguments = ["--cat"]
706+
process.standardInput = stdInput
707+
process.standardOutput = stdOutput
708+
709+
let string = "Hello, World"
710+
let stdInputPipe = stdInput.fileHandleForWriting
711+
XCTAssertNoThrow(try stdInputPipe.write(XCTUnwrap(string.data(using: .utf8))))
712+
stdInputPipe.closeFile()
713+
714+
XCTAssertNoThrow(try process.run())
715+
process.waitUntilExit()
716+
717+
let stdOutputPipe = stdOutput.fileHandleForReading
718+
do {
719+
let readData = try XCTUnwrap(stdOutputPipe.readToEnd())
720+
let readString = String(data: readData, encoding: .utf8)
721+
XCTAssertEqual(string, readString)
722+
} catch {
723+
XCTFail("\(error)")
724+
}
725+
}
699726

700727
static var allTests: [(String, (TestProcess) -> () throws -> Void)] {
701728
var tests = [
@@ -724,6 +751,7 @@ class TestProcess : XCTestCase {
724751
("test_redirect_all_using_nil", test_redirect_all_using_nil),
725752
("test_plutil", test_plutil),
726753
("test_currentDirectory", test_currentDirectory),
754+
("test_pipeCloseBeforeLaunch", test_pipeCloseBeforeLaunch)
727755
]
728756

729757
#if !os(Windows)

0 commit comments

Comments
 (0)