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