Skip to content

Commit 8aa0458

Browse files
elcritchJaremy Creechley
authored andcommitted
Implement zephyr urandom and monotime (#19142)
* implement urandom for Zephyr * add monotime on zephyr Co-authored-by: Jaremy Creechley <[email protected]> (cherry picked from commit 6976d18)
1 parent b9363c8 commit 8aa0458

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

lib/std/monotimes.nim

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,10 @@ when defined(js):
7676
elif defined(posix) and not defined(osx):
7777
import posix
7878

79+
when defined(zephyr):
80+
proc k_uptime_ticks(): int64 {.importc: "k_uptime_ticks", header: "<kernel.h>".}
81+
proc k_ticks_to_ns_floor64(ticks: int64): int64 {.importc: "k_ticks_to_ns_floor64", header: "<kernel.h>".}
82+
7983
elif defined(windows):
8084
proc QueryPerformanceCounter(res: var uint64) {.
8185
importc: "QueryPerformanceCounter", stdcall, dynlib: "kernel32".}
@@ -98,6 +102,9 @@ proc getMonoTime*(): MonoTime {.tags: [TimeEffect].} =
98102
mach_timebase_info(machAbsoluteTimeFreq)
99103
result = MonoTime(ticks: ticks * machAbsoluteTimeFreq.numer div
100104
machAbsoluteTimeFreq.denom)
105+
elif defined(zephyr):
106+
let ticks = k_ticks_to_ns_floor64(k_uptime_ticks())
107+
result = MonoTime(ticks: ticks)
101108
elif defined(posix):
102109
var ts: Timespec
103110
discard clock_gettime(CLOCK_MONOTONIC, ts)

lib/std/sysrand.nim

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ when defined(posix):
6363
import posix
6464

6565
const
66-
batchImplOS = defined(freebsd) or defined(openbsd) or (defined(macosx) and not defined(ios))
66+
batchImplOS = defined(freebsd) or defined(openbsd) or defined(zephyr) or (defined(macosx) and not defined(ios))
6767
batchSize {.used.} = 256
6868

6969
when batchImplOS:
@@ -207,6 +207,16 @@ elif defined(openbsd):
207207
proc getRandomImpl(p: pointer, size: int): int {.inline.} =
208208
result = getentropy(p, cint(size)).int
209209

210+
elif defined(zephyr):
211+
proc sys_csrand_get(dst: pointer, length: csize_t): cint {.importc: "sys_csrand_get", header: "<random/rand32.h>".}
212+
# Fill the destination buffer with cryptographically secure
213+
# random data values
214+
#
215+
216+
proc getRandomImpl(p: pointer, size: int): int {.inline.} =
217+
# 0 if success, -EIO if entropy reseed error
218+
result = sys_csrand_get(p, csize_t(size)).int
219+
210220
elif defined(freebsd):
211221
type cssize_t {.importc: "ssize_t", header: "<sys/types.h>".} = int
212222

0 commit comments

Comments
 (0)