From 5b96aba75d3c31f0ae8d3219a25d454ef9a66da1 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:04:33 +0100 Subject: [PATCH] Sys.random: stop on an error but EINTR, not spin --- diff --git a/lib/Sys.linux-x86_64.raz b/lib/Sys.linux-x86_64.raz index 00f1333..56be717 100644 --- a/lib/Sys.linux-x86_64.raz +++ b/lib/Sys.linux-x86_64.raz @@ -711,14 +711,26 @@ repeat until SYSCALL(230, 1, 1, ADR(t), 0) # -4; (* clock_nanosleep until t, again after EINTR *) end; -(* Fills b with random bytes, from the kernel. *) +(* Ends the program: random bytes can't be faked. *) +proc noRandom; +begin + _ := write(stderr, "Sys.random: the kernel gave no random bytes\n"); + _ := SYSCALL(231, 2); (* exit *) +end; + +(* Fills b with random bytes, from the kernel. Random bytes can't be + faked, so if the kernel can't give them (no getrandom, or a filter + refusing it) it says so on standard error and ends the program by + exit with status 2. *) proc random*(b: []U8); var n, r: INT; begin n := 0; while n < LEN(b) do (* a signal may cut it short *) r := SYSCALL(318, ADR(b[n]), LEN(b) - n, 0); (* getrandom *) - if r > 0 then INC(n, r); end; + if r > 0 then INC(n, r); + elsif r # errIntr then noRandom(); + end; end; end; diff --git a/lib/Sys.raz b/lib/Sys.raz index b658221..c1be9dc 100644 --- a/lib/Sys.raz +++ b/lib/Sys.raz @@ -783,14 +783,26 @@ repeat until C.clock_nanosleep(CAbi.clockMonotonic, CAbi.timerAbstime, ^U8(ADR(t)), nil) # CAbi.eIntr; end; -(* Fills b with random bytes, from the kernel. *) +(* Ends the program: random bytes can't be faked. *) +proc noRandom; +begin + _ := write(stderr, "Sys.random: the kernel gave no random bytes\n"); + C._exit(2); +end; + +(* Fills b with random bytes, from the kernel. Random bytes can't be + faked, so if the kernel can't give them (no getrandom, or a filter + refusing it) it says so on standard error and ends the program by + exit with status 2. *) proc random*(b: []U8); var n, r: INT; begin n := 0; while n < LEN(b) do (* a signal may cut it short *) r := C.getrandom(ADR(b[n]), UINT(LEN(b) - n), 0); - if r > 0 then INC(n, r); end; + if r > 0 then INC(n, r); + elsif (r >= 0) or (failed() # errIntr) then noRandom(); (* r = 0 can't be, and is no progress *) + end; end; end;