From 40522e05dea480e4361a52ba5b06c9569854c896 Mon Sep 17 00:00:00 2001 From: Tristan Horn Date: Wed, 14 Apr 2021 15:39:46 -0700 Subject: [PATCH] Fix memory corruption in io.Writer interface When hooked up to logrus and running multiple log.Info() calls (for example), the bytearray being passed to Write() is reused in the successive calls. As this reference was being passed down through the channel, it resulted in corrupted data and JSON serialization errors. We fix that here by always making a copy before sending to the channel. --- splunk/v2/writer.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/splunk/v2/writer.go b/splunk/v2/writer.go index 37f04be..22e3381 100644 --- a/splunk/v2/writer.go +++ b/splunk/v2/writer.go @@ -50,9 +50,13 @@ func (w *Writer) Write(b []byte) (int, error) { w.errors = make(chan error, bufferSize) go w.listen() }) + // Make a local copy of the bytearray so it doesn't get overwritten by + // the next call to Write() + var b2 = make([]byte, len(b)) + copy(b2, b) // Send the data to the channel w.dataChan <- &message{ - data: b, + data: b2, writtenAt: time.Now(), } // We don't know if we've hit any errors yet, so just say we're good