github.com/dearplain/goloader@v0.0.0-20190107071432-2b1e47d74273/mmap_windows.go (about) 1 package goloader 2 3 import ( 4 "os" 5 "syscall" 6 "unsafe" 7 ) 8 9 func Mmap(size int) ([]byte, error) { 10 11 sizelo := uint32(size >> 32) 12 sizehi := uint32(size) & 0xffffffff 13 h, errno := syscall.CreateFileMapping(syscall.InvalidHandle, nil, 14 syscall.PAGE_EXECUTE_READWRITE, sizelo, sizehi, nil) 15 if h == 0 { 16 return nil, os.NewSyscallError("CreateFileMapping", errno) 17 } 18 19 addr, errno := syscall.MapViewOfFile(h, 20 syscall.FILE_MAP_READ|syscall.FILE_MAP_WRITE|syscall.FILE_MAP_EXECUTE, 21 0, 0, uintptr(size)) 22 if addr == 0 { 23 return nil, os.NewSyscallError("MapViewOfFile", errno) 24 } 25 26 if err := syscall.CloseHandle(syscall.Handle(h)); err != nil { 27 return nil, os.NewSyscallError("CloseHandle", err) 28 } 29 30 var header sliceHeader 31 header.Data = addr 32 header.Len = size 33 header.Cap = size 34 b := *(*[]byte)(unsafe.Pointer(&header)) 35 36 return b, nil 37 } 38 39 func Munmap(b []byte) error { 40 41 addr := (uintptr)(unsafe.Pointer(&b[0])) 42 if err := syscall.UnmapViewOfFile(addr); err != nil { 43 return os.NewSyscallError("UnmapViewOfFile", err) 44 } 45 return nil 46 }