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

source code of compiler-rt/lib/xray/xray_utils.h