This is the mail archive of the
gcc-bugs@gcc.gnu.org
mailing list for the GCC project.
[Bug libstdc++/57920] New: [c++11] Linux: std::random_device reads too much from /dev/urandom
- From: "f dot heckenbach at fh-soft dot de" <gcc-bugzilla at gcc dot gnu dot org>
- To: gcc-bugs at gcc dot gnu dot org
- Date: Wed, 17 Jul 2013 15:31:49 +0000
- Subject: [Bug libstdc++/57920] New: [c++11] Linux: std::random_device reads too much from /dev/urandom
- Auto-submitted: auto-generated
http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57920
Bug ID: 57920
Summary: [c++11] Linux: std::random_device reads too much from
/dev/urandom
Product: gcc
Version: 4.7.2
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: libstdc++
Assignee: unassigned at gcc dot gnu.org
Reporter: f.heckenbach@fh-soft.de
As the test below shows, a single invocation of
std::random_device::operator() reads 4k from /dev/urandom, which is
rather wasteful of the entropy collected in the random device pool.
Of course, in theory, reading 4k and using just 4 bytes of it will
only decrease the entropy by 4 bytes, not 4k, but the kernel can't
know that. When you read 4k from /dev/urandom, it has to assume it
will be used, so it will reduce the entropy by 4k (which is
typically all it has). This means that a subsequent read from
/dev/random (by the same or another process) will block, often
unnecessarily because actually enough entropy was available. This is
particularly annoying since std::random_device is often just used to
seed a PRNG which needs just a few random bytes.
So while buffered reading is almost always a good thing, I contend
it's not in this case. I'd suggest to read unbuffered by default,
which may entail using read() instead of fread().
% cat test.cpp
#include <random>
int main ()
{
std::random_device rd;
rd ();
}
% g++-4.7 -std=c++11 test.cpp
% strace ./a.out
[...]
open("/dev/urandom", O_RDONLY) = 3
fstat64(3, {st_mode=S_IFCHR|0666, st_rdev=makedev(1, 9), ...}) = 0
ioctl(3, SNDCTL_TMR_TIMEBASE or TCGETS, 0xbfffec50) = -1 EINVAL (Invalid
argument)
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) =
0xb7fdf000
read(3, [...], 4096) = 4096
close(3) = 0