Path: blob/main/contrib/llvm-project/libc/src/__support/HashTable/randomness.h
213799 views
//===-- HashTable Randomness ------------------------------------*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#ifndef LLVM_LIBC_SRC___SUPPORT_HASHTABLE_RANDOMNESS_H9#define LLVM_LIBC_SRC___SUPPORT_HASHTABLE_RANDOMNESS_H1011#include "src/__support/common.h"12#include "src/__support/hash.h"13#include "src/__support/macros/attributes.h"14#include "src/__support/macros/config.h"15#if defined(LIBC_HASHTABLE_USE_GETRANDOM)16#include "hdr/errno_macros.h"17#include "src/__support/OSUtil/linux/getrandom.h"18#endif1920namespace LIBC_NAMESPACE_DECL {21namespace internal {22namespace randomness {23// We need an initial state for the hash function. More entropy are to be added24// at the first use and each round of reseeding. The following random numbers25// are generated from https://www.random.org/cgi-bin/randbyte?nbytes=64&format=h26LIBC_INLINE_VAR thread_local HashState state = {270x38049a7ea6f5a79b, 0x45cb02147c3f718a, 0x53eb431c12770718,280x5b55742bd20a2fcb};29LIBC_INLINE_VAR thread_local uint64_t counter = 0;30LIBC_INLINE_VAR constexpr uint64_t RESEED_PERIOD = 1024;31LIBC_INLINE uint64_t next_random_seed() {32if (counter % RESEED_PERIOD == 0) {33uint64_t entropy[2];34entropy[0] = reinterpret_cast<uint64_t>(&entropy);35entropy[1] = reinterpret_cast<uint64_t>(&state);36#if defined(LIBC_HASHTABLE_USE_GETRANDOM)37size_t count = sizeof(entropy);38uint8_t *buffer = reinterpret_cast<uint8_t *>(entropy);39while (count > 0) {40auto len = internal::getrandom(buffer, count, 0);41if (!len.has_value()) {42if (len.error() == ENOSYS)43break;44continue;45}46count -= len.value();47buffer += len.value();48}49#endif50state.update(&entropy, sizeof(entropy));51}52state.update(&counter, sizeof(counter));53counter++;54return state.finish();55}5657} // namespace randomness58} // namespace internal59} // namespace LIBC_NAMESPACE_DECL60#endif // LLVM_LIBC_SRC___SUPPORT_HASHTABLE_RANDOMNESS_H616263