Skip to content

Commit adb2fb0

Browse files
committed
[CompilerPlugin] Exit cleanly
If read(2) returned 0, STDIN is closed. So return nil from 'waitForNextMessage()' so the caller can exit cleanly.
1 parent c830a21 commit adb2fb0

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

Sources/SwiftCompilerPlugin/CompilerPlugin.swift

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -208,21 +208,27 @@ internal struct PluginHostConnection: MessageConnection {
208208
func waitForNextMessage<RX: Decodable>(_ ty: RX.Type) throws -> RX? {
209209
// Read the header (a 64-bit length field in little endian byte order).
210210
let count = try _reading(inputStream, count: 8) { buffer in
211-
UInt64(littleEndian: buffer.loadUnaligned(as: UInt64.self))
211+
return buffer.count == 8 ? UInt64(littleEndian: buffer.loadUnaligned(as: UInt64.self)) : 0
212212
}
213213
guard count >= 2 else {
214+
if count == 0 {
215+
// input stream is closed.
216+
return nil
217+
}
214218
throw PluginMessageError.invalidPayloadSize
215219
}
216220

217221
// Read the JSON payload.
218-
return try _reading(inputStream, count: Int(count)) { buffer in
222+
return try _reading(inputStream, count: Int(count)) { buffer -> RX in
223+
if buffer.count != Int(count) {
224+
throw PluginMessageError.truncatedPayload
225+
}
219226
// Decode and return the message.
220-
try JSON.decode(RX.self, from: buffer.bindMemory(to: UInt8.self))
227+
return try JSON.decode(RX.self, from: buffer.bindMemory(to: UInt8.self))
221228
}
222229
}
223230

224231
enum PluginMessageError: Swift.Error {
225-
case truncatedHeader
226232
case invalidPayloadSize
227233
case truncatedPayload
228234
}
@@ -257,7 +263,8 @@ func _reading<T>(_ fd: CInt, count: Int, _ fn: (UnsafeRawBufferPointer) throws -
257263
while remaining > 0 {
258264
switch read(fd, ptr, remaining) {
259265
case 0:
260-
throw CompilerPluginError(message: "read(2) closed")
266+
// Input is closed.
267+
return try fn(UnsafeRawBufferPointer(start: nil, count: 0))
261268
case -1:
262269
let err = String(cString: strerror(errno))
263270
throw CompilerPluginError(message: "read(2) failed: \(err)")

0 commit comments

Comments
 (0)