|
5 | 5 | package mmap |
6 | 6 |
|
7 | 7 | import ( |
| 8 | + "fmt" |
8 | 9 | "os" |
| 10 | + "unsafe" |
| 11 | + |
| 12 | + "golang.org/x/sys/windows" |
9 | 13 | ) |
10 | 14 |
|
11 | 15 | func mmapFile(f *os.File) (Data, error) { |
12 | | - panic("not implemented yet") |
| 16 | + st, err := f.Stat() |
| 17 | + if err != nil { |
| 18 | + return Data{}, err |
| 19 | + } |
| 20 | + size := st.Size() |
| 21 | + if size == 0 { |
| 22 | + return Data{f, nil}, nil |
| 23 | + } |
| 24 | + h, err := windows.CreateFileMapping(windows.Handle(f.Fd()), nil, windows.PAGE_READONLY, 0, 0, nil) |
| 25 | + if err != nil { |
| 26 | + return Data{}, fmt.Errorf("CreateFileMapping %s: %w", f.Name(), err) |
| 27 | + } |
| 28 | + |
| 29 | + addr, err := windows.MapViewOfFile(h, windows.FILE_MAP_READ, 0, 0, 0) |
| 30 | + if err != nil { |
| 31 | + return Data{}, fmt.Errorf("MapViewOfFile %s: %w", f.Name(), err) |
| 32 | + } |
| 33 | + var info windows.MemoryBasicInformation |
| 34 | + err = windows.VirtualQuery(addr, &info, unsafe.Sizeof(info)) |
| 35 | + if err != nil { |
| 36 | + return Data{}, fmt.Errorf("VirtualQuery %s: %w", f.Name(), err) |
| 37 | + } |
| 38 | + data := unsafe.Slice((*byte)(unsafe.Pointer(addr)), int(info.RegionSize)) |
| 39 | + if len(data) < int(size) { |
| 40 | + // In some cases, especially on 386, we may not receive a in incomplete mapping: |
| 41 | + // one that is shorter than the file itself. Return an error in those cases because |
| 42 | + // incomplete mappings are not useful. |
| 43 | + return Data{}, fmt.Errorf("mmapFile: received incomplete mapping of file") |
| 44 | + } |
| 45 | + return Data{f, data[:int(size)]}, nil |
13 | 46 | } |
0 commit comments