summaryrefslogtreecommitdiff
path: root/lib/scudo/scudo_utils.h
blob: 33798194d618e1562becfe5fd1563b32773aacdd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//===-- scudo_utils.h -------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// Header for scudo_utils.cpp.
///
//===----------------------------------------------------------------------===//

#ifndef SCUDO_UTILS_H_
#define SCUDO_UTILS_H_

#include "sanitizer_common/sanitizer_common.h"

#include <string.h>

namespace __scudo {

template <class Dest, class Source>
INLINE Dest bit_cast(const Source& source) {
  static_assert(sizeof(Dest) == sizeof(Source), "Sizes are not equal!");
  Dest dest;
  memcpy(&dest, &source, sizeof(dest));
  return dest;
}

void NORETURN dieWithMessage(const char *Format, ...);

bool hasHardwareCRC32();

INLINE u64 rotl(const u64 X, int K) {
  return (X << K) | (X >> (64 - K));
}

// XoRoShiRo128+ PRNG (http://xoroshiro.di.unimi.it/).
struct XoRoShiRo128Plus {
 public:
  void init() {
    if (UNLIKELY(!GetRandom(reinterpret_cast<void *>(State), sizeof(State),
                            /*blocking=*/false))) {
      // On some platforms, early processes like `init` do not have an
      // initialized random pool (getrandom blocks and /dev/urandom doesn't
      // exist yet), but we still have to provide them with some degree of
      // entropy. Not having a secure seed is not as problematic for them, as
      // they are less likely to be the target of heap based vulnerabilities
      // exploitation attempts.
      State[0] = NanoTime();
      State[1] = 0;
    }
    fillCache();
  }
  u8 getU8() {
    if (UNLIKELY(isCacheEmpty()))
      fillCache();
    const u8 Result = static_cast<u8>(CachedBytes & 0xff);
    CachedBytes >>= 8;
    CachedBytesAvailable--;
    return Result;
  }
  u64 getU64() { return next(); }

 private:
  u8 CachedBytesAvailable;
  u64 CachedBytes;
  u64 State[2];
  u64 next() {
    const u64 S0 = State[0];
    u64 S1 = State[1];
    const u64 Result = S0 + S1;
    S1 ^= S0;
    State[0] = rotl(S0, 55) ^ S1 ^ (S1 << 14);
    State[1] = rotl(S1, 36);
    return Result;
  }
  bool isCacheEmpty() {
    return CachedBytesAvailable == 0;
  }
  void fillCache() {
    CachedBytes = next();
    CachedBytesAvailable = sizeof(CachedBytes);
  }
};

typedef XoRoShiRo128Plus ScudoPrng;

}  // namespace __scudo

#endif  // SCUDO_UTILS_H_