Skip to content

Commit 21df377

Browse files
authored
Merge pull request swiftlang#296 from benlangmuir/dup-dup2-duparoo
Dup and redirect stdout to defend against accidental print()
2 parents 2840c7d + c508dfd commit 21df377

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

Sources/sourcekit-lsp/main.swift

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,10 +107,20 @@ do {
107107
exit(1)
108108
}
109109

110+
// Dup stdout and redirect the fd to stderr so that a careless print()
111+
// will not break our connection stream.
112+
let realStdout = dup(STDOUT_FILENO)
113+
if realStdout == -1 {
114+
fatalError("failed to dup stdout: \(strerror(errno))")
115+
}
116+
if dup2(STDERR_FILENO, STDOUT_FILENO) == -1 {
117+
fatalError("failed to redirect stdout -> stderr: \(strerror(errno))")
118+
}
119+
110120
let clientConnection = JSONRPCConnection(
111121
protocol: MessageRegistry.lspProtocol,
112122
inFD: STDIN_FILENO,
113-
outFD: STDOUT_FILENO,
123+
outFD: realStdout,
114124
syncRequests: options.syncRequests)
115125

116126
let installPath = AbsolutePath(Bundle.main.bundlePath)

0 commit comments

Comments
 (0)