Skip to content

Commit

Permalink
fix: add runtime.KeepAlive to keep alive descriptors
Browse files Browse the repository at this point in the history
Without them, when we pass the result of Fd() into unix.Syscall, Go runtime is free to call finalizer set in os.newFile.
More info [here](golang/go#34810).

The proper fix is to either:

1. Use unix.Open/unix.Close as descriptors (ints) everywhere in the Device code. This should hide fd's from Go runtime.
2. Use os.File.SyscallConn().Control which guarantees that descriptor survives. This will also do not put fd's into the blocking mode.

Otherwise, even with os.File.Close it's not guaranteed that runtime.SetFinalizer will not come for `os.File.file`.

Signed-off-by: Dmitriy Matrenichev <[email protected]>
  • Loading branch information
DmitriyMV committed Jun 10, 2024
1 parent 1a51f16 commit f4a4030
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions block/device_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"fmt"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"unsafe"
Expand Down Expand Up @@ -45,6 +46,8 @@ func (d *Device) GetSize() (uint64, error) {
return 0, errno
}

runtime.KeepAlive(d)

return devsize, nil
}

Expand All @@ -61,6 +64,8 @@ func (d *Device) GetIOSize() (uint, error) {
}
}

runtime.KeepAlive(d)

return DefaultBlockSize, nil
}

Expand All @@ -72,6 +77,8 @@ func (d *Device) GetSectorSize() uint {
return DefaultBlockSize
}

runtime.KeepAlive(d)

return size
}

Expand All @@ -83,6 +90,8 @@ func (d *Device) IsCD() bool {
return false
}

runtime.KeepAlive(d)

return true
}

Expand All @@ -92,6 +101,8 @@ func (d *Device) IsCDNoMedia() bool {

arg, _, errno := unix.Syscall(unix.SYS_IOCTL, d.f.Fd(), uintptr(CDROM_DRIVE_STATUS), 0)

runtime.KeepAlive(d)

return errno == 0 && (arg == 1 || arg == 2)
}

Expand All @@ -106,6 +117,8 @@ func (d *Device) GetDevNo() (uint64, error) {
return 0, err
}

runtime.KeepAlive(d)

d.devNo = st.Rdev

return d.devNo, nil
Expand Down Expand Up @@ -143,6 +156,8 @@ func (d *Device) IsReadOnly() (bool, error) {
return false, errno
}

runtime.KeepAlive(d)

return flags != 0, nil
}

Expand Down Expand Up @@ -279,6 +294,8 @@ func (d *Device) lock(exclusive bool, flag int) error {
if err := unix.Flock(int(d.f.Fd()), flag); !errors.Is(err, unix.EINTR) {
return err
}

runtime.KeepAlive(d)
}
}

Expand Down

0 comments on commit f4a4030

Please sign in to comment.