[m-rev.] for review: implement the system RNG on Windows

Peter Wang novalazy at gmail.com
Sat Feb 13 12:40:28 AEDT 2021


On Sat, 13 Feb 2021 03:54:24 +1100 Julien Fischer <jfischer at opturion.com> wrote:
> +#elif defined(ML_SYSRAND_IMPL_RAND_S)
> +
> +ML_SystemRandomHandle
> +ML_random_open(MR_Bool *succeeded, MR_String *err_msg)
> +{
> +    *succeeded = MR_TRUE;
> +    *err_msg = MR_make_string_const(\"\");
> +    return 0;
> +}
> +
> +MR_Bool
> +ML_random_close(ML_SystemRandomHandle handle, MR_String *err_msg)
> +{
> +    *err_msg = MR_make_string_const(\"\");
> +    return MR_TRUE;
> +}
> +
> +MR_Bool
> +ML_random_generate_bytes(ML_SystemRandomHandle handle,
> +    unsigned char *buffer, size_t len, MR_String *err_msg)
> +{
> +    int err;
> +    unsigned int n;
> +    unsigned char *bytes = (unsigned char *) &n;

Use a union?

> +    size_t num_to_read = len;
> +    size_t i;
> +
> +    while (num_to_read > 0) {
> +        err = rand_s(&n);
> +        if (err != 0) {
> +            *err_msg = MR_make_string_const(\"rand_s failed\");
> +            return MR_FALSE;
> +        }
> +        for (i = 0; i < 4; i++) {
> +            buffer[num_to_read - 1] = bytes[i];
> +            num_to_read--;
> +            if (num_to_read == 0) {
> +                break;
> +            }
> +        }

Copying backwards is a bit weird, and you could move the if out of the
loop. Obviously not a big deal.

    if (num_to_read <= 4) {
        memcpy(buffer, bytes, num_to_read);
        break;
    } else {
        memcpy(buffer, bytes, 4);
        num_to_read -= 4;
        buffer += 4;
    }

Actually, it would be better to rand_s directly into the output buffer
until the remaining length is less than 4.

> +    }
> +
> +    return MR_TRUE;
> +}

You didn't set *err_msg in this case.

Do you know if it works with MinGW-w64?

Peter


More information about the reviews mailing list