Source file src/crypto/rand/rand_batched.go

     1  // Copyright 2014 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 || freebsd || dragonfly || solaris
     6  
     7  package rand
     8  
     9  import (
    10  	"errors"
    11  	"internal/syscall/unix"
    12  )
    13  
    14  // maxGetRandomRead is platform dependent.
    15  func init() {
    16  	altGetRandom = batched(getRandomBatch, maxGetRandomRead)
    17  }
    18  
    19  // If the kernel is too old to support the getrandom syscall(),
    20  // unix.GetRandom will immediately return ENOSYS and we will then fall back to
    21  // reading from /dev/urandom in rand_unix.go. unix.GetRandom caches the ENOSYS
    22  // result so we only suffer the syscall overhead once in this case.
    23  // If the kernel supports the getrandom() syscall, unix.GetRandom will block
    24  // until the kernel has sufficient randomness (as we don't use GRND_NONBLOCK).
    25  // In this case, unix.GetRandom will not return an error.
    26  func getRandomBatch(p []byte) (err error) {
    27  	n, err := unix.GetRandom(p, 0)
    28  	if n != len(p) {
    29  		return errors.New("short read")
    30  	}
    31  	return err
    32  }
    33  

View as plain text