Support for unpacked ARM packed relocations.
[chromium-blink-merge.git] / base / rand_util_posix.cc
blob0a72a20d6420961e75aabf82f06fff41ca5e1dc1
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"
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <unistd.h>
11 #include "base/file_util.h"
12 #include "base/lazy_instance.h"
13 #include "base/logging.h"
15 namespace {
17 // We keep the file descriptor for /dev/urandom around so we don't need to
18 // reopen it (which is expensive), and since we may not even be able to reopen
19 // it if we are later put in a sandbox. This class wraps the file descriptor so
20 // we can use LazyInstance to handle opening it on the first access.
21 class URandomFd {
22 public:
23 URandomFd() : fd_(open("/dev/urandom", O_RDONLY)) {
24 DCHECK_GE(fd_, 0) << "Cannot open /dev/urandom: " << errno;
27 ~URandomFd() { close(fd_); }
29 int fd() const { return fd_; }
31 private:
32 const int fd_;
35 base::LazyInstance<URandomFd>::Leaky g_urandom_fd = LAZY_INSTANCE_INITIALIZER;
37 } // namespace
39 namespace base {
41 // NOTE: This function must be cryptographically secure. http://crbug.com/140076
42 uint64 RandUint64() {
43 uint64 number;
44 RandBytes(&number, sizeof(number));
45 return number;
48 void RandBytes(void* output, size_t output_length) {
49 const int urandom_fd = g_urandom_fd.Pointer()->fd();
50 const bool success =
51 ReadFromFD(urandom_fd, static_cast<char*>(output), output_length);
52 CHECK(success);
55 int GetUrandomFD(void) {
56 return g_urandom_fd.Pointer()->fd();
59 } // namespace base