golang.org/x/sys@v0.20.1-0.20240517151509-673e0f94c16d/unix/mmap_unix_test.go (about)

     1  // 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  
     5  //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
     6  
     7  package unix_test
     8  
     9  import (
    10  	"runtime"
    11  	"testing"
    12  
    13  	"golang.org/x/sys/unix"
    14  )
    15  
    16  func TestMmap(t *testing.T) {
    17  	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)
    28  	if err != nil {
    29  		t.Fatalf("Mmap: %v", err)
    30  	}
    31  	if err := unix.Mprotect(b, mprotectProt); err != nil {
    32  		t.Fatalf("Mprotect: %v", err)
    33  	}
    34  
    35  	b[0] = 42
    36  
    37  	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  		}
    43  	}
    44  
    45  	if err := unix.Madvise(b, unix.MADV_DONTNEED); err != nil {
    46  		t.Fatalf("Madvise: %v", err)
    47  	}
    48  	if err := unix.Munmap(b); err != nil {
    49  		t.Fatalf("Munmap: %v", err)
    50  	}
    51  }