blob: a60a0f62b94d238bc6d659429e01d5acb5f02a88 [file] [log] [blame]
Rob Pike20acc5c2014-08-11 14:48:46 -07001// Copyright 2014 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
Russ Cox9a761022021-02-19 22:57:36 -05005//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
Rob Pike20acc5c2014-08-11 14:48:46 -07006
Rob Pike8442dd22014-08-11 15:58:26 -07007package unix_test
Rob Pike20acc5c2014-08-11 14:48:46 -07008
9import (
Tony Reixd99a5782018-08-17 10:25:03 +020010 "runtime"
Rob Pike20acc5c2014-08-11 14:48:46 -070011 "testing"
Rob Pike279b3782014-08-12 22:59:00 -070012
Andrew Gerranddea3d762014-11-10 08:56:17 +110013 "golang.org/x/sys/unix"
Rob Pike20acc5c2014-08-11 14:48:46 -070014)
15
16func TestMmap(t *testing.T) {
Tobias Klauser748af6e2023-02-23 17:24:01 +010017 mmapProt := unix.PROT_NONE
18 mprotectProt := unix.PROT_READ | unix.PROT_WRITE
19 // On NetBSD PAX mprotect prohibits setting protection bits
20 // missing from the original mmap call unless explicitly
21 // requested with PROT_MPROTECT.
22 if runtime.GOOS == "netbsd" {
23 // PROT_MPROTECT(x) is defined as ((x) << 3):
24 // https://github.com/NetBSD/src/blob/aba449a55bf91b44bc68f542edd9afa341962b89/sys/sys/mman.h#L73
25 mmapProt = mprotectProt << 3
26 }
27 b, err := unix.Mmap(-1, 0, unix.Getpagesize(), mmapProt, unix.MAP_ANON|unix.MAP_PRIVATE)
Rob Pike20acc5c2014-08-11 14:48:46 -070028 if err != nil {
29 t.Fatalf("Mmap: %v", err)
30 }
Tobias Klauser748af6e2023-02-23 17:24:01 +010031 if err := unix.Mprotect(b, mprotectProt); err != nil {
Tobias Klauser43e60d72017-08-16 17:16:36 +020032 t.Fatalf("Mprotect: %v", err)
33 }
34
35 b[0] = 42
36
Tony Reixd99a5782018-08-17 10:25:03 +020037 if runtime.GOOS == "aix" {
38 t.Skip("msync returns invalid argument for AIX, skipping msync test")
39 } else {
40 if err := unix.Msync(b, unix.MS_SYNC); err != nil {
41 t.Fatalf("Msync: %v", err)
42 }
Tobias Klauser43e60d72017-08-16 17:16:36 +020043 }
Tony Reixd99a5782018-08-17 10:25:03 +020044
Tobias Klauser43e60d72017-08-16 17:16:36 +020045 if err := unix.Madvise(b, unix.MADV_DONTNEED); err != nil {
46 t.Fatalf("Madvise: %v", err)
47 }
Rob Pike8442dd22014-08-11 15:58:26 -070048 if err := unix.Munmap(b); err != nil {
Rob Pike20acc5c2014-08-11 14:48:46 -070049 t.Fatalf("Munmap: %v", err)
50 }
51}