[m-rev.] for comment / review: system random number generator

Julien Fischer jfischer at opturion.com
Thu Jan 28 14:06:40 AEDT 2021

On Thu, 28 Jan 2021, Peter Wang wrote:

> On Wed, 27 Jan 2021 16:42:38 +1100 Julien Fischer <jfischer at opturion.com> wrote:
>> The diff below is a proposed interface for the system random number generator.
>> I would like feedback on its design in general, as well as the names of various
>> things.
>> The diff includes implementations for the C# and Java backends; support for the
>> C backends is NYI, but the plan is as follows:
>>     Windows     - rand_s()
>>     macOS, *BSD - arc4random() and friends
>>     Linux       - getrandom() for kernels / c libs that support it
>>                 - read from /dev/urandom otherwise
>>     Other Unix  - read from /dev/urandom or /dev/random
>>                   as appropriate, or simply not supported.
>> My plan is to commit this diff after review and the add the implementations for
>> the various C platforms separately.  Until the C implementations are complete,
>> the new submodule will not be included in the public library documentation.
>> +    % A handle through which the system RNG can be accessed.
>> +    %
>> +    % In general, it is *not* safe to share system RNG handles across
>> +    % multiple threads. In circumstances where multiple threads require access
>> +    % to the system RNG, each thread should open its own handle.
>> +    %
>> +:- type system_rng.
> Which implementation might this warning apply to?

The motivation for the comment was the C# backend, in particular there's
nothing in the documentation for
System.Security.Cryptography.RandomNumberGenerator that requires the RNG
that implements it to be thread safe.  In practice,
RNGCryptoServiceProvider (which is what it defaults to) is thread safe,
but that is apparently not available on all systems.

> In low-level C .par grades, "threads" might refer to Mercury threads
> that can be moved across OS threads. I could see that being a problem
> if the system RNG has state associated with an OS thread.

There are two cases:

1. when reading from /dev/urandom etc, here there is an fd associated
with the handle, but that's not tied to any particular OS thread.

2. Everything else.  These all pretty much result in a system call
at some level and do not have any state associated with user threads.

>> +do_open_system_rng(_, _, _, _, _) :-
>> +    private_builtin.sorry("No system RNG available").
> This should return an error.



More information about the reviews mailing list