/usr/games/random bug?

Brooks Davis brooks at one-eyed-alien.net
Mon Dec 20 17:47:54 PST 2004


On Mon, Dec 20, 2004 at 07:13:49PM -0600, James R. Van Artsalen wrote:
> 5-stable "/usr/games/random -e 99" seems to always return 0, which makes 
> it very predictable.
> 
> 5.2.1 does this too.  But i386 4.x seems to work as expected (an exit 
> value between 0 and 98 inclusive).
> 
> The source code line in question is
> 
>              return (int)((denom * random()) / LONG_MAX);
> 
> the assembler code is
> 
>        .p2align 3
> .LC17:
>        .long   0
>        .long   1006632960
> 
>        call    random
>        cvtsi2sdq       %rax, %xmm0
>        mulsd   24(%rsp), %xmm0
>        mulsd   .LC17(%rip), %xmm0
>        cvttsd2si       %xmm0, %eax
>        jmp     .L1
> 
> I'm not familiar enough with IEEE fp rules or amd64 fp coding to say why 
> this doesn't work, nor if this source code is even reasonable.

I believe the code is bogus.  The code says, compute a long
(denom*random) then divide it by the largest possiable value you can
store in a long.  Since integer math in C truncates, the value should
always be 0 unless denom*random() happens to be LONG_MAX in which case
it will be 1.

It's intresting that this code ever worked.  A quick check indicates
that this doesn not work on alpha or sparc64.  Apparently no one noticed
that this code has been broken for over a decade (we got it from UCB).
NetBSD switched from LONG_MAX to MAXRANDOM in 2000, but apparently
didn't actually read the code since it also has the bug.

-- Brooks

-- 
Any statement of the form "X is the one, true Y" is FALSE.
PGP fingerprint 655D 519C 26A7 82E7 2529  9BF0 5D8E 8BE9 F238 1AD4
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://lists.freebsd.org/pipermail/freebsd-amd64/attachments/20041220/f6d453e6/attachment.bin


More information about the freebsd-amd64 mailing list