...
1
2
3
4
5
6
7
8
9
10 package unix_test
11
12 import (
13 "fmt"
14 "os"
15 "path/filepath"
16 "testing"
17
18 "golang.org/x/sys/unix"
19 )
20
21 func TestMmap(t *testing.T) {
22 tempdir := t.TempDir()
23 filename := filepath.Join(tempdir, "memmapped_file")
24
25 destination, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0700)
26 if err != nil {
27 t.Fatal("os.Create:", err)
28 return
29 }
30
31 fmt.Fprintf(destination, "%s\n", "0 <- Flipped between 0 and 1 when test runs successfully")
32 fmt.Fprintf(destination, "%s\n", "//Do not change contents - mmap test relies on this")
33 destination.Close()
34
35 fd, err := unix.Open(filename, unix.O_RDWR, 0777)
36 if err != nil {
37 t.Fatalf("Open: %v", err)
38 }
39
40 b, err := unix.Mmap(fd, 0, 8, unix.PROT_READ, unix.MAP_SHARED)
41 if err != nil {
42 t.Fatalf("Mmap: %v", err)
43 }
44
45 if err := unix.Mprotect(b, unix.PROT_READ|unix.PROT_WRITE); err != nil {
46 t.Fatalf("Mprotect: %v", err)
47 }
48
49
50 flagWasZero := true
51 if b[0] == '0' {
52 b[0] = '1'
53 } else if b[0] == '1' {
54 b[0] = '0'
55 flagWasZero = false
56 }
57
58 if err := unix.Msync(b, unix.MS_SYNC); err != nil {
59 t.Fatalf("Msync: %v", err)
60 }
61
62
63 buf, err := os.ReadFile(filename)
64 if err != nil {
65 t.Fatalf("Could not read mmapped file from disc for test: %v", err)
66 }
67 if flagWasZero && buf[0] != '1' || !flagWasZero && buf[0] != '0' {
68 t.Error("Flag flip in MAP_SHARED mmapped file not visible")
69 }
70
71 if err := unix.Munmap(b); err != nil {
72 t.Fatalf("Munmap: %v", err)
73 }
74 }
75
76 func TestMmapPtr(t *testing.T) {
77 p, err := unix.MmapPtr(-1, 0, nil, uintptr(2*unix.Getpagesize()),
78 unix.PROT_READ|unix.PROT_WRITE, unix.MAP_ANON|unix.MAP_PRIVATE)
79 if err != nil {
80 t.Fatalf("MmapPtr: %v", err)
81 }
82
83 *(*byte)(p) = 42
84
85 if err := unix.MunmapPtr(p, uintptr(2*unix.Getpagesize())); err != nil {
86 t.Fatalf("MunmapPtr: %v", err)
87 }
88 }
89
View as plain text