Source file src/crypto/internal/fips140/nistec/p256_asm_test.go

     1  // Copyright 2024 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 (amd64 || arm64 || ppc64le || s390x) && !purego && (linux || darwin)
     6  
     7  package nistec
     8  
     9  import (
    10  	"syscall"
    11  	"testing"
    12  	"unsafe"
    13  )
    14  
    15  // dangerousObjs allocates a pair of T one at the start of a page, another at
    16  // the end. Any access beyond or before the page boundary should cause a fault.
    17  func dangerousObjs[T any](t *testing.T) (start *T, end *T) {
    18  	startBuf, endBuf := boundarySlices(t, int(unsafe.Sizeof(*new(T))))
    19  	return (*T)(unsafe.Pointer(&startBuf[0])), (*T)(unsafe.Pointer(&endBuf[0]))
    20  }
    21  
    22  // boundarySlices is a copy of [crypto/internal/cryptotest.BoundarySlices].
    23  func boundarySlices(t *testing.T, size int) (start, end []byte) {
    24  	pageSize := syscall.Getpagesize()
    25  	needPages := 2 + (2*size+pageSize-1)/pageSize
    26  	b, err := syscall.Mmap(0, 0, needPages*pageSize, syscall.PROT_READ|syscall.PROT_WRITE,
    27  		syscall.MAP_ANON|syscall.MAP_PRIVATE)
    28  	if err != nil {
    29  		t.Fatalf("mmap failed: %v", err)
    30  	}
    31  	t.Cleanup(func() { syscall.Munmap(b) })
    32  	if err := syscall.Mprotect(b[:pageSize], syscall.PROT_NONE); err != nil {
    33  		t.Fatalf("mprotect low failed: %v", err)
    34  	}
    35  	if err := syscall.Mprotect(b[len(b)-pageSize:], syscall.PROT_NONE); err != nil {
    36  		t.Fatalf("mprotect high failed: %v", err)
    37  	}
    38  	return b[pageSize : pageSize+size : pageSize+size],
    39  		b[len(b)-pageSize-size : len(b)-pageSize : len(b)-pageSize]
    40  }
    41  
    42  func TestP256SelectAffinePageBoundary(t *testing.T) {
    43  	var out p256AffinePoint
    44  	begintp, endtp := dangerousObjs[p256AffineTable](t)
    45  	for i := 0; i < 31; i++ {
    46  		p256SelectAffine(&out, begintp, i)
    47  		p256SelectAffine(&out, endtp, i)
    48  	}
    49  }
    50  
    51  func TestP256SelectPageBoundary(t *testing.T) {
    52  	var out P256Point
    53  	begintp, endtp := dangerousObjs[p256Table](t)
    54  	for i := 0; i < 15; i++ {
    55  		p256Select(&out, begintp, i)
    56  		p256Select(&out, endtp, i)
    57  	}
    58  }
    59  

View as plain text