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

     1  // Copyright 2020 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 zos && s390x
     6  
     7  // This test is based on mmap_unix_test, but tweaked for z/OS, which does not support memadvise
     8  // or anonymous mmapping.
     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  	// Flip flag in test file via mapped memory
    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  	// Read file from FS to ensure flag flipped after msync
    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  }