1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/rand_util.h"
13 #include "base/check.h"
14 #include "base/files/file_util.h"
15 #include "base/no_destructor.h"
16 #include "base/posix/eintr_wrapper.h"
20 // We keep the file descriptor for /dev/urandom around so we don't need to
21 // reopen it (which is expensive), and since we may not even be able to reopen
22 // it if we are later put in a sandbox. This class wraps the file descriptor so
23 // we can use a static-local variable to handle opening it on the first access.
27 // AIX has no 64-bit support for open falgs such as -
28 // O_CLOEXEC, O_NOFOLLOW and O_TTY_INIT
29 URandomFd() : fd_(HANDLE_EINTR(open("/dev/urandom", O_RDONLY))) {
30 DPCHECK(fd_ >= 0) << "Cannot open /dev/urandom";
33 URandomFd() : fd_(HANDLE_EINTR(open("/dev/urandom", O_RDONLY | O_CLOEXEC))) {
34 DPCHECK(fd_ >= 0) << "Cannot open /dev/urandom";
38 ~URandomFd() { close(fd_); }
40 int fd() const { return fd_; }
50 void RandBytes(void* output, size_t output_length) {
51 const int urandom_fd = GetUrandomFD();
53 ReadFromFD(urandom_fd, static_cast<char*>(output), output_length);
58 static NoDestructor<URandomFd> urandom_fd;
59 return urandom_fd->fd();