Skip to content

Commit

Permalink
mem/file.go - Fix some races in accessing fields of FileData
Browse files Browse the repository at this point in the history
* Splitting SetModeTime to avoid double locking
* Adding locks all over the place.
  • Loading branch information
corentone committed Aug 25, 2017
1 parent 9be6508 commit b08da71
Showing 1 changed file with 31 additions and 7 deletions.
38 changes: 31 additions & 7 deletions mem/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,14 +74,24 @@ func CreateDir(name string) *FileData {
}

func ChangeFileName(f *FileData, newname string) {
f.Lock()
defer f.Unlock()
f.name = newname
}

func SetMode(f *FileData, mode os.FileMode) {
f.Lock()
defer f.Unlock()
f.mode = mode
}

func SetModTime(f *FileData, mtime time.Time) {
f.Lock()
defer f.Unlock()
setModTime(f, mtime)
}

func setModTime(f *FileData, mtime time.Time) {
f.modtime = mtime
}

Expand All @@ -102,7 +112,7 @@ func (f *File) Close() error {
f.fileData.Lock()
f.closed = true
if !f.readOnly {
SetModTime(f.fileData, time.Now())
setModTime(f.fileData, time.Now())
}
f.fileData.Unlock()
return nil
Expand Down Expand Up @@ -197,7 +207,7 @@ func (f *File) Truncate(size int64) error {
} else {
f.fileData.data = f.fileData.data[0:size]
}
SetModTime(f.fileData, time.Now())
setModTime(f.fileData, time.Now())
return nil
}

Expand Down Expand Up @@ -236,7 +246,7 @@ func (f *File) Write(b []byte) (n int, err error) {
f.fileData.data = append(f.fileData.data[:cur], b...)
f.fileData.data = append(f.fileData.data, tail...)
}
SetModTime(f.fileData, time.Now())
setModTime(f.fileData, time.Now())

atomic.StoreInt64(&f.at, int64(len(f.fileData.data)))
return
Expand Down Expand Up @@ -264,14 +274,28 @@ func (s *FileInfo) Name() string {
_, name := filepath.Split(s.name)
return name
}
func (s *FileInfo) Mode() os.FileMode { return s.mode }
func (s *FileInfo) ModTime() time.Time { return s.modtime }
func (s *FileInfo) IsDir() bool { return s.dir }
func (s *FileInfo) Sys() interface{} { return nil }
func (s *FileInfo) Mode() os.FileMode {
s.Lock()
defer s.Unlock()
return s.mode
}
func (s *FileInfo) ModTime() time.Time {
s.Lock()
defer s.Unlock()
return s.modtime
}
func (s *FileInfo) IsDir() bool {
s.Lock()
defer s.Unlock()
return s.dir
}
func (s *FileInfo) Sys() interface{} { return nil }
func (s *FileInfo) Size() int64 {
if s.IsDir() {
return int64(42)
}
s.Lock()
defer s.Unlock()
return int64(len(s.data))
}

Expand Down

0 comments on commit b08da71

Please sign in to comment.