2 * Copyright 2014 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include <folly/Random.h>
25 #include <glog/logging.h>
26 #include <folly/File.h>
27 #include <folly/FileUtil.h>
33 void readRandomDevice(void* data, size_t size) {
34 // Keep it open for the duration of the program
35 static File randomDevice("/dev/urandom");
36 PCHECK(readFull(randomDevice.fd(), data, size) == size);
39 class BufferedRandomDevice {
41 static constexpr size_t kDefaultBufferSize = 128;
43 explicit BufferedRandomDevice(size_t bufferSize = kDefaultBufferSize);
45 void get(void* data, size_t size) {
46 if (LIKELY(size <= remaining())) {
47 memcpy(data, ptr_, size);
50 getSlow(static_cast<unsigned char*>(data), size);
55 void getSlow(unsigned char* data, size_t size);
57 inline size_t remaining() const {
58 return buffer_.get() + bufferSize_ - ptr_;
61 const size_t bufferSize_;
62 std::unique_ptr<unsigned char[]> buffer_;
66 BufferedRandomDevice::BufferedRandomDevice(size_t bufferSize)
67 : bufferSize_(bufferSize),
68 buffer_(new unsigned char[bufferSize]),
69 ptr_(buffer_.get() + bufferSize) { // refill on first use
72 void BufferedRandomDevice::getSlow(unsigned char* data, size_t size) {
73 DCHECK_GT(size, remaining());
74 if (size >= bufferSize_) {
75 // Just read directly.
76 readRandomDevice(data, size);
80 size_t copied = remaining();
81 memcpy(data, ptr_, copied);
86 readRandomDevice(buffer_.get(), bufferSize_);
89 memcpy(data, ptr_, size);
96 void Random::secureRandom(void* data, size_t size) {
97 static ThreadLocal<BufferedRandomDevice> bufferedRandomDevice;
98 bufferedRandomDevice->get(data, size);
101 ThreadLocalPRNG::ThreadLocalPRNG() {
102 static folly::ThreadLocal<ThreadLocalPRNG::LocalInstancePRNG> localInstance;
103 local_ = localInstance.get();
106 class ThreadLocalPRNG::LocalInstancePRNG {
108 LocalInstancePRNG() : rng(Random::create()) { }
110 Random::DefaultGenerator rng;
113 uint32_t ThreadLocalPRNG::getImpl(LocalInstancePRNG* local) {