Merge pull request #307 from fyrchik/fix-windows-readonly

Fix readonly file mapping on windows
pull/363/head
Benjamin Wang 2022-12-21 09:12:26 +08:00 committed by GitHub
commit dd0ab6da68
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 8 additions and 4 deletions

View File

@ -62,24 +62,28 @@ func funlock(db *DB) error {
// mmap memory maps a DB's data file. // mmap memory maps a DB's data file.
// Based on: https://github.com/edsrzf/mmap-go // Based on: https://github.com/edsrzf/mmap-go
func mmap(db *DB, sz int) error { func mmap(db *DB, sz int) error {
var sizelo, sizehi uint32
if !db.readOnly { if !db.readOnly {
// Truncate the database to the size of the mmap. // Truncate the database to the size of the mmap.
if err := db.file.Truncate(int64(sz)); err != nil { if err := db.file.Truncate(int64(sz)); err != nil {
return fmt.Errorf("truncate: %s", err) return fmt.Errorf("truncate: %s", err)
} }
sizehi = uint32(sz >> 32)
sizelo = uint32(sz) & 0xffffffff
} }
// Open a file mapping handle. // Open a file mapping handle.
sizelo := uint32(sz >> 32) h, errno := syscall.CreateFileMapping(syscall.Handle(db.file.Fd()), nil, syscall.PAGE_READONLY, sizehi, sizelo, nil)
sizehi := uint32(sz) & 0xffffffff
h, errno := syscall.CreateFileMapping(syscall.Handle(db.file.Fd()), nil, syscall.PAGE_READONLY, sizelo, sizehi, nil)
if h == 0 { if h == 0 {
return os.NewSyscallError("CreateFileMapping", errno) return os.NewSyscallError("CreateFileMapping", errno)
} }
// Create the memory map. // Create the memory map.
addr, errno := syscall.MapViewOfFile(h, syscall.FILE_MAP_READ, 0, 0, uintptr(sz)) addr, errno := syscall.MapViewOfFile(h, syscall.FILE_MAP_READ, 0, 0, 0)
if addr == 0 { if addr == 0 {
// Do our best and report error returned from MapViewOfFile.
_ = syscall.CloseHandle(h)
return os.NewSyscallError("MapViewOfFile", errno) return os.NewSyscallError("MapViewOfFile", errno)
} }