Source file src/crypto/internal/cryptotest/boundary.go

     1  // Copyright 2026 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 || darwin
     6  
     7  package cryptotest
     8  
     9  import (
    10  	"syscall"
    11  	"testing"
    12  )
    13  
    14  // BoundarySlices allocates a pair of slices of the given size one at the start
    15  // of a page, another at the end. Any access beyond or before the slice
    16  // boundaries should cause a fault.
    17  func BoundarySlices(t *testing.T, size int) (start, end []byte) {
    18  	pageSize := syscall.Getpagesize()
    19  	needPages := 2 + (2*size+pageSize-1)/pageSize
    20  	b, err := syscall.Mmap(0, 0, needPages*pageSize, syscall.PROT_READ|syscall.PROT_WRITE,
    21  		syscall.MAP_ANON|syscall.MAP_PRIVATE)
    22  	if err != nil {
    23  		t.Fatalf("mmap failed: %v", err)
    24  	}
    25  	t.Cleanup(func() { syscall.Munmap(b) })
    26  	if err := syscall.Mprotect(b[:pageSize], syscall.PROT_NONE); err != nil {
    27  		t.Fatalf("mprotect low failed: %v", err)
    28  	}
    29  	if err := syscall.Mprotect(b[len(b)-pageSize:], syscall.PROT_NONE); err != nil {
    30  		t.Fatalf("mprotect high failed: %v", err)
    31  	}
    32  	return b[pageSize : pageSize+size : pageSize+size],
    33  		b[len(b)-pageSize-size : len(b)-pageSize : len(b)-pageSize]
    34  }
    35  

View as plain text