| 1 |
// Copyright 2021 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 |
package unix |
| 6 |
|
| 7 |
import ( |
| 8 |
"sync/atomic" |
| 9 |
"syscall" |
| 10 |
) |
| 11 |
|
| 12 |
//extern getrandom |
| 13 |
func libc_getrandom(*byte, uintptr, uint32) uintptr |
| 14 |
|
| 15 |
var getrandomUnsupported int32 // atomic |
| 16 |
|
| 17 |
// GetRandomFlag is a flag supported by the getrandom system call. |
| 18 |
type GetRandomFlag uintptr |
| 19 |
|
| 20 |
const ( |
| 21 |
// GRND_NONBLOCK means return EAGAIN rather than blocking. |
| 22 |
GRND_NONBLOCK GetRandomFlag = 0x0001 |
| 23 |
|
| 24 |
// GRND_RANDOM means use the /dev/random pool instead of /dev/urandom. |
| 25 |
GRND_RANDOM GetRandomFlag = 0x0002 |
| 26 |
) |
| 27 |
|
| 28 |
// GetRandom calls the getrandom system call. |
| 29 |
func GetRandom(p []byte, flags GetRandomFlag) (n int, err error) { |
| 30 |
if len(p) == 0 { |
| 31 |
return 0, nil |
| 32 |
} |
| 33 |
if atomic.LoadInt32(&getrandomUnsupported) != 0 { |
| 34 |
return 0, syscall.ENOSYS |
| 35 |
} |
| 36 |
syscall.Entersyscall() |
| 37 |
r1 := libc_getrandom(&p[0], uintptr(len(p)), uint32(flags)) |
| 38 |
syscall.Exitsyscall() |
| 39 |
if r1 == 0 { |
| 40 |
errno := syscall.GetErrno() |
| 41 |
if errno == syscall.ENOSYS { |
| 42 |
atomic.StoreInt32(&getrandomUnsupported, 1) |
| 43 |
} |
| 44 |
return 0, errno |
| 45 |
} |
| 46 |
return int(r1), nil |
| 47 |
} |