This source file includes following definitions.
- fd
- RandUint64
- RandBytes
- GetUrandomFD
#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 {
class URandomFd {
public:
URandomFd() : fd_(open("/dev/urandom", O_RDONLY)) {
DCHECK_GE(fd_, 0) << "Cannot open /dev/urandom: " << errno;
}
~URandomFd() { close(fd_); }
int fd() const { return fd_; }
private:
const int fd_;
};
base::LazyInstance<URandomFd>::Leaky g_urandom_fd = LAZY_INSTANCE_INITIALIZER;
}
namespace base {
uint64 RandUint64() {
uint64 number;
RandBytes(&number, sizeof(number));
return number;
}
void RandBytes(void* output, size_t output_length) {
const int urandom_fd = g_urandom_fd.Pointer()->fd();
const bool success =
ReadFromFD(urandom_fd, static_cast<char*>(output), output_length);
CHECK(success);
}
int GetUrandomFD(void) {
return g_urandom_fd.Pointer()->fd();
}
}