edsrzf / mmap-go

A portable mmap package for Go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Unmap on Windows fails

ncw opened this issue · comments

package main

import (
	"log"

	mmap "github.com/edsrzf/mmap-go"
)

func main() {
	const size = 1024 * 1024
	mem, err := mmap.MapRegion(nil, size, mmap.RDWR, mmap.ANON, 0)
	if err != nil {
		log.Fatalf("mmap: failed to allocate memory for buffer: %v", err)
	}
	log.Printf("memory %p", mem)
	err = mem.Unmap()
	if err != nil {
		log.Fatalf("mmap: failed to unmap memory for buffer: %v", err)
	}

}

This program works fine on linux, but under windows it prints this

X:\>go run mmap.go
2019/01/23 21:41:00 memory 0x31ba0000
2019/01/23 21:41:00 mmap: failed to unmap memory for buffer: FlushFileBuffers: The handle is invalid.
exit status 1

This is because FlushFileBuffers is being called on an anonymous handle.

This fixes it

--- a/vendor/github.com/edsrzf/mmap-go/mmap_windows.go
+++ b/vendor/github.com/edsrzf/mmap-go/mmap_windows.go
@@ -101,7 +101,7 @@ func (m MMap) flush() error {
 		return errors.New("unknown base address")
 	}
 
-	if handle.writable {
+	if handle.writable && handle.file != windows.Handle(^uintptr(0)) {
 		if err := windows.FlushFileBuffers(handle.file); err != nil {
 			return os.NewSyscallError("FlushFileBuffers", err)
 		}

Which I'll supply as a pull request in a moment