macOS use SecRandomCopyBytes instead of getentropy (#20466)

* On macOS use SecRandomCopyBytes instead of getentropy (which is only available on macOS 10.12+)

* Change passL to passl
This commit is contained in:
Matt Haggard 2022-10-05 13:59:10 -04:00 • committed by GitHub
commit 594e93a66b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -20,7 +20,7 @@
## | :--- | ----: | ## | :--- | ----: |
## | Windows | `BCryptGenRandom`_ | ## | Windows | `BCryptGenRandom`_ |
## | Linux | `getrandom`_ | ## | Linux | `getrandom`_ |
## | MacOSX | `getentropy`_ | ## | MacOSX | `SecRandomCopyBytes`_ |
## | iOS | `SecRandomCopyBytes`_ | ## | iOS | `SecRandomCopyBytes`_ |
## | OpenBSD | `getentropy openbsd`_ | ## | OpenBSD | `getentropy openbsd`_ |
## | FreeBSD | `getrandom freebsd`_ | ## | FreeBSD | `getrandom freebsd`_ |
@ -66,7 +66,7 @@ when defined(nimPreviewSlimSystem):
import std/assertions import std/assertions
const const
batchImplOS = defined(freebsd) or defined(openbsd) or defined(zephyr) or (defined(macosx) and not defined(ios)) batchImplOS = defined(freebsd) or defined(openbsd) or defined(zephyr)
batchSize {.used.} = 256 batchSize {.used.} = 256
when batchImplOS: when batchImplOS:
@ -231,8 +231,8 @@ elif defined(freebsd):
proc getRandomImpl(p: pointer, size: int): int {.inline.} = proc getRandomImpl(p: pointer, size: int): int {.inline.} =
result = getrandom(p, csize_t(size), 0) result = getrandom(p, csize_t(size), 0)
elif defined(ios): elif defined(ios) or defined(macosx):
{.passL: "-framework Security".} {.passl: "-framework Security".}
const errSecSuccess = 0 ## No error. const errSecSuccess = 0 ## No error.
@ -254,19 +254,6 @@ elif defined(ios):
result = secRandomCopyBytes(nil, csize_t(size), addr dest[0]) result = secRandomCopyBytes(nil, csize_t(size), addr dest[0])
elif defined(macosx):
const sysrandomHeader = """#include <Availability.h>
#include <sys/random.h>
"""
proc getentropy(p: pointer, size: csize_t): cint {.importc: "getentropy", header: sysrandomHeader.}
# getentropy() fills a buffer with random data, which can be used as input
# for process-context pseudorandom generators like arc4random(3).
# The maximum buffer size permitted is 256 bytes.
proc getRandomImpl(p: pointer, size: int): int {.inline.} =
result = getentropy(p, csize_t(size)).int
else: else:
template urandomImpl(result: var int, dest: var openArray[byte]) = template urandomImpl(result: var int, dest: var openArray[byte]) =
let size = dest.len let size = dest.len