From 5712b1198ec3d28acd4727df7924ec3038ce093f Mon Sep 17 00:00:00 2001 From: jiangpengfei Date: Tue, 12 Mar 2019 20:59:39 -0400 Subject: [PATCH] qemu/qmp: fix readLoop() reuse scanner.Bytes() underlying array problem Since []byte channel type transfer slice info(include slice underlying array pointer, len, cap) between channel sender and receiver. scanner.Bytes() function returned slice's underlying array may point to data that will be overwritten by a subsequent call to Scan(reference from: https://golang.org/pkg/bufio/#Scanner.Bytes), which may make consecutive scan() call write the read data into the same underlying array which causes receiver read mixed data,so we need to copy line to new allocated space and then send to channel receiver to solve this problem. Fixes: #88 Signed-off-by: jiangpengfei --- qemu/qmp.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/qemu/qmp.go b/qemu/qmp.go index 9b21d96480..28a76b0b03 100644 --- a/qemu/qmp.go +++ b/qemu/qmp.go @@ -247,7 +247,16 @@ func (q *QMP) readLoop(fromVMCh chan<- []byte) { if q.cfg.Logger.V(1) { q.cfg.Logger.Infof("%s", string(line)) } - fromVMCh <- line + + // Since []byte channel type transfer slice info(include slice underlying array pointer, len, cap) + // between channel sender and receiver. scanner.Bytes() returned slice's underlying array + // may point to data that will be overwritten by a subsequent call to Scan(reference from: + // https://golang.org/pkg/bufio/#Scanner.Bytes), which may make receiver read mixed data, + // so we need to copy line to new allocated space and then send to channel receiver + sendLine := make([]byte, len(line)) + copy(sendLine, line) + + fromVMCh <- sendLine } close(fromVMCh) }