Debian Codegraph @

debian/go/src/golang.org/x/telemetry/internal/mmap/mmap_windows.go

raw symbols SCIP
1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package mmap
6
7 import (
8 "fmt"
9 "os"
10 "syscall"
11 "unsafe"
12
13 "golang.org/x/sys/windows"
14 )
15
16 func mmapFile(f *os.File, previous *Data) (Data, error) {
17 if previous != nil {
18 munmapFile(*previous)
19 }
20 st, err := f.Stat()
21 if err != nil {
22 return Data{}, err
23 }
24 size := st.Size()
25 if size == 0 {
26 return Data{f, nil, nil}, nil
27 }
28 // set the min and max sizes to zero to map the whole file, as described in
29 // https://learn.microsoft.com/en-us/windows/win32/memory/creating-a-file-mapping-object#file-mapping-size
30 h, err := windows.CreateFileMapping(windows.Handle(f.Fd()), nil, syscall.PAGE_READWRITE, 0, 0, nil)
31 if err != nil {
32 return Data{}, fmt.Errorf("CreateFileMapping %s: %w", f.Name(), err)
33 }
34 // the mapping extends from zero to the end of the file mapping
35 // https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-mapviewoffile
36 addr, err := windows.MapViewOfFile(h, syscall.FILE_MAP_READ|syscall.FILE_MAP_WRITE, 0, 0, 0)
37 if err != nil {
38 return Data{}, fmt.Errorf("MapViewOfFile %s: %w", f.Name(), err)
39 }
40 // need to remember addr and h for unmapping
41 return Data{f, unsafe.Slice((*byte)(unsafe.Pointer(addr)), size), h}, nil
42 }
43
44 func munmapFile(d Data) error {
45 err := windows.UnmapViewOfFile(uintptr(unsafe.Pointer(&d.Data[0])))
46 x, ok := d.Windows.(windows.Handle)
47 if ok {
48 windows.CloseHandle(x)
49 }
50 d.f.Close()
51 return err
52 }