From eedcf11a9988828af1005d92040b5a652968b967 Mon Sep 17 00:00:00 2001 From: Yasuhiro Matsumoto Date: Fri, 10 Jul 2026 17:05:17 +0900 Subject: [PATCH] Guard shared gob encoder with a mutex --- client.go | 2 +- server.go | 2 +- util.go | 21 ++++++++++++++++++++- util_test.go | 2 +- 4 files changed, 23 insertions(+), 4 deletions(-) diff --git a/client.go b/client.go index 082077c..83215ac 100644 --- a/client.go +++ b/client.go @@ -21,7 +21,7 @@ func client(addr string, args []string) int { } defer conn.Close() - enc, dec := gob.NewEncoder(conn), gob.NewDecoder(conn) + enc, dec := newMsgEncoder(conn), gob.NewDecoder(conn) cmd := exec.Command(args[0], args[1:]...) diff --git a/server.go b/server.go index e0c45da..55db437 100644 --- a/server.go +++ b/server.go @@ -55,7 +55,7 @@ func server(args []string) int { } defer conn.Close() - enc, dec := gob.NewEncoder(conn), gob.NewDecoder(conn) + enc, dec := newMsgEncoder(conn), gob.NewDecoder(conn) err = enc.Encode(os.Environ()) if err != nil { diff --git a/util.go b/util.go index 56876aa..d05fc6a 100644 --- a/util.go +++ b/util.go @@ -6,6 +6,7 @@ package main import ( "encoding/gob" "io" + "sync" "syscall" ) @@ -16,7 +17,25 @@ type msg struct { Data []byte } -func msgWrite(enc *gob.Encoder, typ string) io.WriteCloser { +// msgEncoder is a gob encoder that is safe for concurrent use, since the +// stdout/stderr writers and the main goroutine all encode to a single +// connection. +type msgEncoder struct { + mu sync.Mutex + enc *gob.Encoder +} + +func newMsgEncoder(w io.Writer) *msgEncoder { + return &msgEncoder{enc: gob.NewEncoder(w)} +} + +func (e *msgEncoder) Encode(v interface{}) error { + e.mu.Lock() + defer e.mu.Unlock() + return e.enc.Encode(v) +} + +func msgWrite(enc *msgEncoder, typ string) io.WriteCloser { r, w := io.Pipe() go func() { defer r.Close() diff --git a/util_test.go b/util_test.go index 0c5be58..0c85374 100644 --- a/util_test.go +++ b/util_test.go @@ -10,7 +10,7 @@ func TestMsgWrite(t *testing.T) { tests := []string{"foo", "bar", "baz"} pr, pw := io.Pipe() - wc := msgWrite(gob.NewEncoder(pw), "test") + wc := msgWrite(newMsgEncoder(pw), "test") go func() { for _, test := range tests {