Subject: Re: bug#32605: [w64] (random) never returns negative

From: Andy Moreton <[email-masked]>
Date: Thu, 12 Aug 2021 21:34:09 +0100

On Thu 12 Aug 2021, Eli Zaretskii wrote:

>> From: Lars Ingebrigtsen <[email-masked]>
>> Cc: [email-masked], Eli Zaretskii <[email-masked]>
>> Date: Thu, 12 Aug 2021 15:17:46 +0200
>> 
>> Andy Moreton <[email-masked]> writes:
>> 
>> >> This bug seems specific to 64 bit Windows builds.
>> >
>> > ON 64bit Windows, sysdep.c sets RAND_BITS to 31, but random (in w32.c)
>> > only provides 30 bits. It looks like the mixing in get_random does not
>> > result in the top fixnum bit being set.
>
> The 'random' emulation in w32.c was never adapted to w64.

Surely real the problem is that RAND_BITS is 31, but the random() in
w32.c does not provide 31 random bits (and thus fails to meet the API
contract).

In 32bit builds this problem is hidden because 30 bits are sufficient
for a fixnum, so the value of bit30 in the result is ignored.

On 64bit builds, 62 bits are needed for a fixnum, and trying to assemble
a random number from multiple components does not work if RAND_BITS says
31 bits are usable, but the highest bit in that value is always zero.

Also see 

> Instead of calling rand_as183 one more time, perhaps it's better to
> trivially transform the value we have?  Something like
>
>     int val = ((rand_as183 () << 15) | rand_as183 ());
>   #ifdef __x86_64__
>     return 2 * val - 0x3FFFFFFF;
>   #else
>     return val;
>   #endif
>
> Andy, can you test this, please?

That does not produce any negative random numbers within a reasonable
number of attempts (a few dozen calls).

Instead, calling rand_as183 again (as below) does produce positive and
negative random numbers on 32bit and 64bit builds with a similar number
of attempts:

return ((rand_as183 () << 30) | (rand_as183 () << 15) | rand_as183 ());

While this may be less efficient, it at least meets the contract of
providing 31 random bits.

    AndyM