mmap_windows.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // +build windows
  2. /*
  3. * Copyright 2017 Dgraph Labs, Inc. and Contributors
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. package y
  18. import (
  19. "fmt"
  20. "os"
  21. "syscall"
  22. "unsafe"
  23. )
  24. func Mmap(fd *os.File, write bool, size int64) ([]byte, error) {
  25. protect := syscall.PAGE_READONLY
  26. access := syscall.FILE_MAP_READ
  27. if write {
  28. protect = syscall.PAGE_READWRITE
  29. access = syscall.FILE_MAP_WRITE
  30. }
  31. fi, err := fd.Stat()
  32. if err != nil {
  33. return nil, err
  34. }
  35. // Truncate the database to the size of the mmap.
  36. if fi.Size() < size {
  37. if err := fd.Truncate(size); err != nil {
  38. return nil, fmt.Errorf("truncate: %s", err)
  39. }
  40. }
  41. // Open a file mapping handle.
  42. sizelo := uint32(size >> 32)
  43. sizehi := uint32(size) & 0xffffffff
  44. handler, err := syscall.CreateFileMapping(syscall.Handle(fd.Fd()), nil,
  45. uint32(protect), sizelo, sizehi, nil)
  46. if err != nil {
  47. return nil, os.NewSyscallError("CreateFileMapping", err)
  48. }
  49. // Create the memory map.
  50. addr, err := syscall.MapViewOfFile(handler, uint32(access), 0, 0, uintptr(size))
  51. if addr == 0 {
  52. return nil, os.NewSyscallError("MapViewOfFile", err)
  53. }
  54. // Close mapping handle.
  55. if err := syscall.CloseHandle(syscall.Handle(handler)); err != nil {
  56. return nil, os.NewSyscallError("CloseHandle", err)
  57. }
  58. // Slice memory layout
  59. // Copied this snippet from golang/sys package
  60. var sl = struct {
  61. addr uintptr
  62. len int
  63. cap int
  64. }{addr, int(size), int(size)}
  65. // Use unsafe to turn sl into a []byte.
  66. data := *(*[]byte)(unsafe.Pointer(&sl))
  67. return data, nil
  68. }
  69. func Munmap(b []byte) error {
  70. return syscall.UnmapViewOfFile(uintptr(unsafe.Pointer(&b[0])))
  71. }
  72. func Madvise(b []byte, readahead bool) error {
  73. // Do Nothing. We don’t care about this setting on Windows
  74. return nil
  75. }