1package util
2
3import (
4 "context"
5 "os"
6 "reflect"
7 "unsafe"
8
9 "github.com/tetratelabs/wazero/api"
10 "golang.org/x/sys/windows"
11)
12
13type MappedRegion struct {
14 windows.Handle
15 Data []byte
16 addr uintptr
17}
18
19func MapRegion(ctx context.Context, mod api.Module, f *os.File, offset int64, size int32) (*MappedRegion, error) {
20 h, err := windows.CreateFileMapping(windows.Handle(f.Fd()), nil, windows.PAGE_READWRITE, 0, 0, nil)
21 if h == 0 {
22 return nil, err
23 }
24
25 a, err := windows.MapViewOfFile(h, windows.FILE_MAP_WRITE,
26 uint32(offset>>32), uint32(offset), uintptr(size))
27 if a == 0 {
28 windows.CloseHandle(h)
29 return nil, err
30 }
31
32 ret := &MappedRegion{Handle: h, addr: a}
33 // SliceHeader, although deprecated, avoids a go vet warning.
34 sh := (*reflect.SliceHeader)(unsafe.Pointer(&ret.Data))
35 sh.Len = int(size)
36 sh.Cap = int(size)
37 sh.Data = a
38 return ret, nil
39}
40
41func (r *MappedRegion) Unmap() error {
42 if r.Data == nil {
43 return nil
44 }
45 err := windows.UnmapViewOfFile(r.addr)
46 if err != nil {
47 return err
48 }
49 r.Data = nil
50 return windows.CloseHandle(r.Handle)
51}