Skip to content

Commit eeba90f

Browse files
noborumadeadprogram
authored andcommitted
properly handle unix read on directory
1 parent 6507765 commit eeba90f

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

src/os/file_anyos.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//go:build !baremetal && !js && !wasm_unknown && !nintendoswitch
22

3-
// Portions copyright 2009 The Go Authors. All rights reserved.
3+
// Portions copyright 2009-2024 The Go Authors. All rights reserved.
44
// Use of this source code is governed by a BSD-style
55
// license that can be found in the LICENSE file.
66

@@ -97,6 +97,11 @@ type unixFileHandle uintptr
9797
// read and any error encountered. At end of file, Read returns 0, io.EOF.
9898
func (f unixFileHandle) Read(b []byte) (n int, err error) {
9999
n, err = syscall.Read(syscallFd(f), b)
100+
// In case of EISDIR, n == -1.
101+
// This breaks the assumption that n always represent the number of read bytes.
102+
if err == syscall.EISDIR {
103+
n = 0
104+
}
100105
err = handleSyscallError(err)
101106
if n == 0 && len(b) > 0 && err == nil {
102107
err = io.EOF

src/os/file_anyos_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,3 +185,22 @@ func TestClose(t *testing.T) {
185185
}
186186
}
187187
}
188+
189+
func TestReadOnDir(t *testing.T) {
190+
name := TempDir() + "/_os_test_TestReadOnDir"
191+
defer Remove(name)
192+
f, err := OpenFile(name, O_RDWR|O_CREATE, 0644)
193+
if err != nil {
194+
t.Errorf("OpenFile %s: %s", name, err)
195+
return
196+
}
197+
var buf [32]byte
198+
n, err := f.Read(buf[:])
199+
if err == nil {
200+
t.Errorf("Error expected")
201+
return
202+
}
203+
if n != 0 {
204+
t.Errorf("Wrong read bytes: %s", err)
205+
}
206+
}

0 commit comments

Comments
 (0)