1 //===-- xray_utils.h --------------------------------------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file is a part of XRay, a dynamic runtime instrumentation system.
11 //
12 // Some shared utilities for the XRay runtime implementation.
13 //
14 //===----------------------------------------------------------------------===//
15 #ifndef XRAY_UTILS_H
16 #define XRAY_UTILS_H
17
18 #include <cstddef>
19 #include <cstdint>
20 #include <sys/types.h>
21 #include <utility>
22
23 #include "sanitizer_common/sanitizer_common.h"
24 #if SANITIZER_FUCHSIA
25 #include <zircon/types.h>
26 #endif
27
28 namespace __xray {
29
30 class LogWriter {
31 public:
32 #if SANITIZER_FUCHSIA
LogWriter(zx_handle_t Vmo)33 LogWriter(zx_handle_t Vmo) : Vmo(Vmo) {}
34 #else
35 explicit LogWriter(int Fd) : Fd(Fd) {}
36 #endif
37 ~LogWriter();
38
39 // Write a character range into a log.
40 void WriteAll(const char *Begin, const char *End);
41
42 void Flush();
43
44 // Returns a new log instance initialized using the flag-provided values.
45 static LogWriter *Open();
46 // Closes and deallocates the log instance.
47 static void Close(LogWriter *LogWriter);
48
49 private:
50 #if SANITIZER_FUCHSIA
51 zx_handle_t Vmo = ZX_HANDLE_INVALID;
52 uint64_t Offset = 0;
53 #else
54 int Fd = -1;
55 #endif
56 };
57
gcd(size_t a,size_t b)58 constexpr size_t gcd(size_t a, size_t b) {
59 return (b == 0) ? a : gcd(b, a % b);
60 }
61
lcm(size_t a,size_t b)62 constexpr size_t lcm(size_t a, size_t b) { return a * b / gcd(a, b); }
63
nearest_boundary(size_t number,size_t multiple)64 constexpr size_t nearest_boundary(size_t number, size_t multiple) {
65 return multiple * ((number / multiple) + (number % multiple ? 1 : 0));
66 }
67
next_pow2_helper(size_t num,size_t acc)68 constexpr size_t next_pow2_helper(size_t num, size_t acc) {
69 return (1u << acc) >= num ? (1u << acc) : next_pow2_helper(num, acc + 1);
70 }
71
next_pow2(size_t number)72 constexpr size_t next_pow2(size_t number) {
73 return next_pow2_helper(number, 1);
74 }
75
max(T & A,T & B)76 template <class T> constexpr T &max(T &A, T &B) { return A > B ? A : B; }
77
min(T & A,T & B)78 template <class T> constexpr T &min(T &A, T &B) { return A <= B ? A : B; }
79
diff(uintptr_t A,uintptr_t B)80 constexpr ptrdiff_t diff(uintptr_t A, uintptr_t B) {
81 return max(A, B) - min(A, B);
82 }
83
84 } // namespace __xray
85
86 #endif // XRAY_UTILS_H
87