Debian Codegraph @

mmap_windows.go

raw symbols SCIP
1 //go:build windows && !appengine
2
3 package maxminddb
4
5 import (
6 "errors"
7 "os"
8 "unsafe"
9
10 "golang.org/x/sys/windows"
11 )
12
13 // mmap maps a file into memory and returns a byte slice.
14 func mmap(fd, length int) ([]byte, error) {
15 // Create a file mapping
16 handle, err := windows.CreateFileMapping(
17 windows.Handle(fd),
18 nil,
19 windows.PAGE_READONLY,
20 0,
21 0,
22 nil,
23 )
24 if err != nil {
25 return nil, os.NewSyscallError("CreateFileMapping", err)
26 }
27 defer windows.CloseHandle(handle)
28
29 // Map the file into memory
30 addrUintptr, err := windows.MapViewOfFile(
31 handle,
32 windows.FILE_MAP_READ,
33 0,
34 0,
35 0,
36 )
37 if err != nil {
38 return nil, os.NewSyscallError("MapViewOfFile", err)
39 }
40
41 // When there's not enough address space for the whole file (e.g. large
42 // files on 32-bit systems), MapViewOfFile may return a partial mapping.
43 // Query the region size and fail on partial mappings.
44 var info windows.MemoryBasicInformation
45 if err := windows.VirtualQuery(addrUintptr, &info, unsafe.Sizeof(info)); err != nil {
46 _ = windows.UnmapViewOfFile(addrUintptr)
47 return nil, os.NewSyscallError("VirtualQuery", err)
48 }
49 if info.RegionSize < uintptr(length) {
50 _ = windows.UnmapViewOfFile(addrUintptr)
51 return nil, errors.New("file too large")
52 }
53
54 // Workaround for unsafeptr check in go vet, see
55 // https://github.com/golang/go/issues/58625
56 addr := *(*unsafe.Pointer)(unsafe.Pointer(&addrUintptr))
57 return unsafe.Slice((*byte)(addr), length), nil
58 }
59
60 // munmap unmaps a memory-mapped file and releases associated resources.
61 func munmap(b []byte) error {
62 // Convert slice to base address and length
63 data := unsafe.SliceData(b)
64 addr := uintptr(unsafe.Pointer(data))
65
66 // Unmap the memory
67 if err := windows.UnmapViewOfFile(addr); err != nil {
68 return os.NewSyscallError("UnmapViewOfFile", err)
69 }
70 return nil
71 }