Skip to content

os: fix race condition in readdir by atomically initializing dirinfo #71501

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions src/os/dir_plan9.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,19 @@ import (
)

func (file *File) readdir(n int, mode readdirMode) (names []string, dirents []DirEntry, infos []FileInfo, err error) {
// If this file has no dirinfo, create one.
d := file.dirinfo.Load()
if d == nil {
d = new(dirInfo)
file.dirinfo.Store(d)
var d *dirInfo
for {
d = file.dirinfo.Load()
if d != nil {
break
}
newD := new(dirInfo)
if file.dirinfo.CompareAndSwap(nil, newD) {
d = newD
break
}
}

d.mu.Lock()
defer d.mu.Unlock()

Expand Down
16 changes: 12 additions & 4 deletions src/os/dir_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,19 @@ func (d *dirInfo) close() {

func (f *File) readdir(n int, mode readdirMode) (names []string, dirents []DirEntry, infos []FileInfo, err error) {
// If this file has no dirInfo, create one.
d := f.dirinfo.Load()
if d == nil {
d = new(dirInfo)
f.dirinfo.Store(d)
var d *dirInfo
for {
d = f.dirinfo.Load()
if d != nil {
break
}
newD := new(dirInfo)
if f.dirinfo.CompareAndSwap(nil, newD) {
d = newD
break
}
}

d.mu.Lock()
defer d.mu.Unlock()
if d.buf == nil {
Expand Down