diff options
author | deanm@chromium.org <deanm@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2009-06-26 10:00:02 +0000 |
---|---|---|
committer | deanm@chromium.org <deanm@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2009-06-26 10:00:02 +0000 |
commit | 09e5f47ad0ab092bdf03025eb72c2a29cb9fe2ec (patch) | |
tree | ecd27d2681cca0a9decb304ccaf5916ab521dd1e /base/rand_util_posix.cc | |
parent | 5ae918ab1e21c4647739c586299dd9a5f5ae0890 (diff) | |
download | chromium_src-09e5f47ad0ab092bdf03025eb72c2a29cb9fe2ec.zip chromium_src-09e5f47ad0ab092bdf03025eb72c2a29cb9fe2ec.tar.gz chromium_src-09e5f47ad0ab092bdf03025eb72c2a29cb9fe2ec.tar.bz2 |
Cache the file descriptor for /dev/urandom to avoid needing to reopen it for every call.
Patch by Mike Mammarella.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/144010
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@19352 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'base/rand_util_posix.cc')
-rw-r--r-- | base/rand_util_posix.cc | 33 |
1 files changed, 30 insertions, 3 deletions
diff --git a/base/rand_util_posix.cc b/base/rand_util_posix.cc index b4f3ac2..a2bdeb8 100644 --- a/base/rand_util_posix.cc +++ b/base/rand_util_posix.cc @@ -4,24 +4,51 @@ #include "base/rand_util.h" +#include <errno.h> #include <fcntl.h> #include <unistd.h> #include "base/file_util.h" +#include "base/lazy_instance.h" #include "base/logging.h" +namespace { + +// We keep the file descriptor for /dev/urandom around so we don't need to +// reopen it (which is expensive), and since we may not even be able to reopen +// it if we are later put in a sandbox. This class wraps the file descriptor so +// we can use LazyInstance to handle opening it on the first access. +class URandomFd { + public: + URandomFd() { + fd_ = open("/dev/urandom", O_RDONLY); + CHECK(fd_ >= 0) << "Cannot open /dev/urandom: " << errno; + } + + ~URandomFd() { + close(fd_); + } + + int fd() const { return fd_; } + + private: + int fd_; +}; + +base::LazyInstance<URandomFd> g_urandom_fd(base::LINKER_INITIALIZED); + +} // namespace + namespace base { uint64 RandUint64() { uint64 number; - int urandom_fd = open("/dev/urandom", O_RDONLY); - CHECK(urandom_fd >= 0); + int urandom_fd = g_urandom_fd.Pointer()->fd(); bool success = file_util::ReadFromFD(urandom_fd, reinterpret_cast<char*>(&number), sizeof(number)); CHECK(success); - close(urandom_fd); return number; } |