github.com/gidoBOSSftw5731/go/src@v0.0.0-20210226122457-d24b0edbf019/runtime/debug/panic_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 aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd
     6  // +build aix darwin dragonfly freebsd linux netbsd openbsd
     7  
     8  // TODO: test on Windows?
     9  
    10  package debug_test
    11  
    12  import (
    13  	"runtime"
    14  	"runtime/debug"
    15  	"syscall"
    16  	"testing"
    17  	"unsafe"
    18  )
    19  
    20  func TestPanicOnFault(t *testing.T) {
    21  	if runtime.GOARCH == "s390x" {
    22  		t.Skip("s390x fault addresses are missing the low order bits")
    23  	}
    24  	if runtime.GOOS == "ios" {
    25  		t.Skip("iOS doesn't provide fault addresses")
    26  	}
    27  	m, err := syscall.Mmap(-1, 0, 0x1000, syscall.PROT_READ /* Note: no PROT_WRITE */, syscall.MAP_SHARED|syscall.MAP_ANON)
    28  	if err != nil {
    29  		t.Fatalf("can't map anonymous memory: %s", err)
    30  	}
    31  	defer syscall.Munmap(m)
    32  	old := debug.SetPanicOnFault(true)
    33  	defer debug.SetPanicOnFault(old)
    34  	const lowBits = 0x3e7
    35  	defer func() {
    36  		r := recover()
    37  		if r == nil {
    38  			t.Fatalf("write did not fault")
    39  		}
    40  		type addressable interface {
    41  			Addr() uintptr
    42  		}
    43  		a, ok := r.(addressable)
    44  		if !ok {
    45  			t.Fatalf("fault does not contain address")
    46  		}
    47  		want := uintptr(unsafe.Pointer(&m[lowBits]))
    48  		got := a.Addr()
    49  		if got != want {
    50  			t.Fatalf("fault address %x, want %x", got, want)
    51  		}
    52  	}()
    53  	m[lowBits] = 1 // will fault
    54  }