github.com/pkujhd/goloader@v0.0.0-20240411034752-1a28096bd7bd/mmap/mmap_windows.go (about)

     1  //go:build windows
     2  // +build windows
     3  
     4  package mmap
     5  
     6  import (
     7  	"os"
     8  	"syscall"
     9  	"unsafe"
    10  )
    11  
    12  // See reflect/value.go sliceHeader
    13  type sliceHeader struct {
    14  	Data uintptr
    15  	Len  int
    16  	Cap  int
    17  }
    18  
    19  func MakeThreadJITCodeExecutable(ptr uintptr, len int) {
    20  }
    21  
    22  func Mmap(size int) ([]byte, error) {
    23  
    24  	sizelo := uint32(size >> 32)
    25  	sizehi := uint32(size) & 0xFFFFFFFF
    26  	h, errno := syscall.CreateFileMapping(syscall.InvalidHandle, nil,
    27  		syscall.PAGE_EXECUTE_READWRITE, sizelo, sizehi, nil)
    28  	if h == 0 {
    29  		return nil, os.NewSyscallError("CreateFileMapping", errno)
    30  	}
    31  
    32  	addr, errno := syscall.MapViewOfFile(h,
    33  		syscall.FILE_MAP_READ|syscall.FILE_MAP_WRITE|syscall.FILE_MAP_EXECUTE,
    34  		0, 0, uintptr(size))
    35  	if addr == 0 {
    36  		return nil, os.NewSyscallError("MapViewOfFile", errno)
    37  	}
    38  
    39  	if err := syscall.CloseHandle(syscall.Handle(h)); err != nil {
    40  		return nil, os.NewSyscallError("CloseHandle", err)
    41  	}
    42  
    43  	var header sliceHeader
    44  	header.Data = addr
    45  	header.Len = size
    46  	header.Cap = size
    47  	b := *(*[]byte)(unsafe.Pointer(&header))
    48  
    49  	return b, nil
    50  }
    51  
    52  func MmapData(size int) ([]byte, error) {
    53  
    54  	sizelo := uint32(size >> 32)
    55  	sizehi := uint32(size) & 0xFFFFFFFF
    56  	h, errno := syscall.CreateFileMapping(syscall.InvalidHandle, nil,
    57  		syscall.PAGE_READWRITE, sizelo, sizehi, nil)
    58  	if h == 0 {
    59  		return nil, os.NewSyscallError("CreateFileMapping", errno)
    60  	}
    61  
    62  	addr, errno := syscall.MapViewOfFile(h,
    63  		syscall.FILE_MAP_READ|syscall.FILE_MAP_WRITE,
    64  		0, 0, uintptr(size))
    65  	if addr == 0 {
    66  		return nil, os.NewSyscallError("MapViewOfFile", errno)
    67  	}
    68  
    69  	if err := syscall.CloseHandle(syscall.Handle(h)); err != nil {
    70  		return nil, os.NewSyscallError("CloseHandle", err)
    71  	}
    72  
    73  	var header sliceHeader
    74  	header.Data = addr
    75  	header.Len = size
    76  	header.Cap = size
    77  	b := *(*[]byte)(unsafe.Pointer(&header))
    78  
    79  	return b, nil
    80  }
    81  
    82  func Munmap(b []byte) error {
    83  
    84  	addr := (uintptr)(unsafe.Pointer(&b[0]))
    85  	if err := syscall.UnmapViewOfFile(addr); err != nil {
    86  		return os.NewSyscallError("UnmapViewOfFile", err)
    87  	}
    88  	return nil
    89  }