From 4b34438f7a67ee5f45cc6132e2bad873a20324e9 Mon Sep 17 00:00:00 2001 From: Tobias Klauser Date: Fri, 5 Apr 2019 17:09:22 +0200 Subject: [PATCH] unix: allow empty string argument to SetsockoptString Don't panic with "index out of range" on empty string argument. Follows CL 170937 which did the sane for package syscall. Updates golang/go#31277 Change-Id: I4feb796d0d58d3637428ae69997cfa3ec28a6b01 Reviewed-on: https://go-review.googlesource.com/c/sys/+/170957 Run-TryBot: Tobias Klauser TryBot-Result: Gobot Gobot Reviewed-by: Brad Fitzpatrick --- unix/syscall_unix.go | 6 +++++- unix/syscall_unix_test.go | 8 ++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/unix/syscall_unix.go b/unix/syscall_unix.go index 0ed1d58d..3de37566 100644 --- a/unix/syscall_unix.go +++ b/unix/syscall_unix.go @@ -351,7 +351,11 @@ func SetsockoptLinger(fd, level, opt int, l *Linger) (err error) { } func SetsockoptString(fd, level, opt int, s string) (err error) { - return setsockopt(fd, level, opt, unsafe.Pointer(&[]byte(s)[0]), uintptr(len(s))) + var p unsafe.Pointer + if len(s) > 0 { + p = unsafe.Pointer(&[]byte(s)[0]) + } + return setsockopt(fd, level, opt, p, uintptr(len(s))) } func SetsockoptTimeval(fd, level, opt int, tv *Timeval) (err error) { diff --git a/unix/syscall_unix_test.go b/unix/syscall_unix_test.go index 264305f2..14d25ca7 100644 --- a/unix/syscall_unix_test.go +++ b/unix/syscall_unix_test.go @@ -403,6 +403,14 @@ func TestSeekFailure(t *testing.T) { } } +func TestSetsockoptString(t *testing.T) { + // should not panic on empty string, see issue #31277 + err := unix.SetsockoptString(-1, 0, 0, "") + if err == nil { + t.Fatalf("SetsockoptString: did not fail") + } +} + func TestDup(t *testing.T) { file, err := ioutil.TempFile("", "TestDup") if err != nil {