...

Source file src/golang.org/x/sys/unix/mremap_test.go

Documentation: golang.org/x/sys/unix

     1  // Copyright 2023 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 linux || netbsd
     6  
     7  package unix_test
     8  
     9  import (
    10  	"testing"
    11  	"unsafe"
    12  
    13  	"golang.org/x/sys/unix"
    14  )
    15  
    16  func TestMremap(t *testing.T) {
    17  	b, err := unix.Mmap(-1, 0, unix.Getpagesize(), unix.PROT_NONE, unix.MAP_ANON|unix.MAP_PRIVATE)
    18  	if err != nil {
    19  		t.Fatalf("Mmap: %v", err)
    20  	}
    21  	if err := unix.Mprotect(b, unix.PROT_READ|unix.PROT_WRITE); err != nil {
    22  		t.Fatalf("Mprotect: %v", err)
    23  	}
    24  
    25  	b[0] = 42
    26  
    27  	bNew, err := unix.Mremap(b, unix.Getpagesize()*2, unix.MremapMaymove)
    28  	if err != nil {
    29  		t.Fatalf("Mremap2: %v", err)
    30  	}
    31  	bNew[unix.Getpagesize()+1] = 84 // checks
    32  
    33  	if bNew[0] != 42 {
    34  		t.Fatal("first element value was changed")
    35  	}
    36  	if len(bNew) != unix.Getpagesize()*2 {
    37  		t.Fatal("new memory len not equal to specified len")
    38  	}
    39  	if cap(bNew) != unix.Getpagesize()*2 {
    40  		t.Fatal("new memory cap not equal to specified len")
    41  	}
    42  
    43  	_, err = unix.Mremap(b, unix.Getpagesize(), unix.MremapFixed)
    44  	if err != unix.EINVAL {
    45  		t.Fatalf("remapping to a fixed address; got %v, want %v", err, unix.EINVAL)
    46  	}
    47  }
    48  
    49  func TestMremapPtr(t *testing.T) {
    50  	p1, err := unix.MmapPtr(-1, 0, nil, uintptr(2*unix.Getpagesize()),
    51  		unix.PROT_READ|unix.PROT_WRITE, unix.MAP_ANON|unix.MAP_PRIVATE)
    52  	if err != nil {
    53  		t.Fatalf("MmapPtr: %v", err)
    54  	}
    55  
    56  	p2 := unsafe.Add(p1, unix.Getpagesize())
    57  	if err := unix.MunmapPtr(p2, uintptr(unix.Getpagesize())); err != nil {
    58  		t.Fatalf("MunmapPtr: %v", err)
    59  	}
    60  
    61  	*(*byte)(p1) = 42
    62  
    63  	if _, err := unix.MremapPtr(
    64  		p1, uintptr(unix.Getpagesize()),
    65  		p2, uintptr(unix.Getpagesize()),
    66  		unix.MremapFixed|unix.MremapMaymove); err != nil {
    67  		t.Fatalf("MremapPtr: %v", err)
    68  	}
    69  
    70  	if got := *(*byte)(p2); got != 42 {
    71  		t.Errorf("got %d, want 42", got)
    72  	}
    73  
    74  	if err := unix.MunmapPtr(p2, uintptr(unix.Getpagesize())); err != nil {
    75  		t.Fatalf("MunmapPtr: %v", err)
    76  	}
    77  }
    78  

View as plain text