Date: Sat, 21 May 2016 15:40:00 -0500 From: Pedro Giffuni <pfg@FreeBSD.org> To: cem@FreeBSD.org Cc: src-committers@freebsd.org, svn-src-all@freebsd.org, svn-src-head@freebsd.org Subject: Re: svn commit: r300377 - head/sys/compat/ndis Message-ID: <a88c14ea-ee78-54de-6142-08a561a49d98@FreeBSD.org> In-Reply-To: <CAG6CVpXjU3tHdar7d=xyr%2BTmffg0NrQu3q7SD=b6%2BjF=yvVr-Q@mail.gmail.com> References: <201605211752.u4LHqiHQ031457@repo.freebsd.org> <CAG6CVpXjU3tHdar7d=xyr%2BTmffg0NrQu3q7SD=b6%2BjF=yvVr-Q@mail.gmail.com>
next in thread | previous in thread | raw e-mail | index | archive | help
On 05/21/16 14:05, Conrad Meyer wrote: > On Sat, May 21, 2016 at 10:52 AM, Pedro F. Giffuni <pfg@freebsd.org> wrote: >> Author: pfg >> Date: Sat May 21 17:52:44 2016 >> New Revision: 300377 >> URL: https://svnweb.freebsd.org/changeset/base/300377 >> >> Log: >> ndis(4): Avoid overflow. >> >> This is a long standing problem: our random() function returns an >> unsigned integer but the rand provided by ndis(4) returns an int. >> Scale it down. >> >> MFC after: 2 weeks >> >> Modified: >> head/sys/compat/ndis/subr_ntoskrnl.c >> >> Modified: head/sys/compat/ndis/subr_ntoskrnl.c >> ============================================================================== >> --- head/sys/compat/ndis/subr_ntoskrnl.c Sat May 21 17:38:43 2016 (r300376) >> +++ head/sys/compat/ndis/subr_ntoskrnl.c Sat May 21 17:52:44 2016 (r300377) >> @@ -3189,7 +3189,7 @@ static int >> rand(void) >> { >> >> - return (random()); >> + return (random() / 2 + 1); >> } >> >> static void >> > > > Won't this still return a negative integer in many cases? > > random(9) returns u_long, whereas this rand() routine returns 'int'. > > Even on architectures where long is the same size as ordinary > integers, the range of possible results of the 'random() / 2 + 1' > expression, before implicit cast to signed, is [1, 2^31] (inclusive). According to: sys/libkern/random.c The result is uniform on [0, 2^31 - 1]. > 2^31 is not representable by typical signed 32-bit integers, so this > will wrap to INT_MIN. Also, I'm not sure why zero is excluded from > the range. > It is not a good reason but the zero is sometimes inconvenient: if the value is going to be used as a multiplier in some calculation it will basically kill the random component. > On architectures where long is larger than ordinary integers, this > expression has no hope of fitting in the non-negative range of a > signed integer. > > Why not instead: > > return ((u_int)random() / 2); > TBH, I have seen the same conversion formula over and over and I just repeated it, so I am glad you are asking the question. Hopefully some else has a better answer? ;). Pedro. Pedro. > Best, > Conrad >
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?a88c14ea-ee78-54de-6142-08a561a49d98>