Skip to content

Commit c508dfd

Browse files
committed
Dup and redirect stdout to defend against accidental print()
We currently have a regression where sourcekit-lsp stops working in some packages, because swiftpm started printing a warning to stdout. While we should also fix swiftpm, it behooves us to be more robust in sourcekit-lsp in case this happens again. Dup stdout for use by the protocol, and redirect the stdout file descriptor to stderr, which does not interfere with the protocol.
1 parent 2840c7d commit c508dfd

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)