]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/xray/xray_x86_64.cc
Merge compiler-rt trunk r300890, and update build glue.
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / xray / xray_x86_64.cc
1 #include "cpuid.h"
2 #include "sanitizer_common/sanitizer_common.h"
3 #include "xray_defs.h"
4 #include "xray_interface_internal.h"
5
6 #include <atomic>
7 #include <cstdint>
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <iterator>
11 #include <limits>
12 #include <tuple>
13 #include <unistd.h>
14
15 namespace __xray {
16
17 static std::pair<ssize_t, bool>
18 retryingReadSome(int Fd, char *Begin, char *End) XRAY_NEVER_INSTRUMENT {
19   auto BytesToRead = std::distance(Begin, End);
20   ssize_t BytesRead;
21   ssize_t TotalBytesRead = 0;
22   while (BytesToRead && (BytesRead = read(Fd, Begin, BytesToRead))) {
23     if (BytesRead == -1) {
24       if (errno == EINTR)
25         continue;
26       Report("Read error; errno = %d\n", errno);
27       return std::make_pair(TotalBytesRead, false);
28     }
29
30     TotalBytesRead += BytesRead;
31     BytesToRead -= BytesRead;
32     Begin += BytesRead;
33   }
34   return std::make_pair(TotalBytesRead, true);
35 }
36
37 static bool readValueFromFile(const char *Filename,
38                               long long *Value) XRAY_NEVER_INSTRUMENT {
39   int Fd = open(Filename, O_RDONLY | O_CLOEXEC);
40   if (Fd == -1)
41     return false;
42   static constexpr size_t BufSize = 256;
43   char Line[BufSize] = {};
44   ssize_t BytesRead;
45   bool Success;
46   std::tie(BytesRead, Success) = retryingReadSome(Fd, Line, Line + BufSize);
47   close(Fd);
48   if (!Success)
49     return false;
50   char *End = nullptr;
51   long long Tmp = internal_simple_strtoll(Line, &End, 10);
52   bool Result = false;
53   if (Line[0] != '\0' && (*End == '\n' || *End == '\0')) {
54     *Value = Tmp;
55     Result = true;
56   }
57   return Result;
58 }
59
60 uint64_t getTSCFrequency() XRAY_NEVER_INSTRUMENT {
61   long long TSCFrequency = -1;
62   if (readValueFromFile("/sys/devices/system/cpu/cpu0/tsc_freq_khz",
63                         &TSCFrequency)) {
64     TSCFrequency *= 1000;
65   } else if (readValueFromFile(
66                  "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq",
67                  &TSCFrequency)) {
68     TSCFrequency *= 1000;
69   } else {
70     Report("Unable to determine CPU frequency for TSC accounting.\n");
71   }
72   return TSCFrequency == -1 ? 0 : static_cast<uint64_t>(TSCFrequency);
73 }
74
75 static constexpr uint8_t CallOpCode = 0xe8;
76 static constexpr uint16_t MovR10Seq = 0xba41;
77 static constexpr uint16_t Jmp9Seq = 0x09eb;
78 static constexpr uint8_t JmpOpCode = 0xe9;
79 static constexpr uint8_t RetOpCode = 0xc3;
80
81 static constexpr int64_t MinOffset{std::numeric_limits<int32_t>::min()};
82 static constexpr int64_t MaxOffset{std::numeric_limits<int32_t>::max()};
83
84 bool patchFunctionEntry(const bool Enable, const uint32_t FuncId,
85                         const XRaySledEntry &Sled,
86                         void (*Trampoline)()) XRAY_NEVER_INSTRUMENT {
87   // Here we do the dance of replacing the following sled:
88   //
89   // xray_sled_n:
90   //   jmp +9
91   //   <9 byte nop>
92   //
93   // With the following:
94   //
95   //   mov r10d, <function id>
96   //   call <relative 32bit offset to entry trampoline>
97   //
98   // We need to do this in the following order:
99   //
100   // 1. Put the function id first, 2 bytes from the start of the sled (just
101   // after the 2-byte jmp instruction).
102   // 2. Put the call opcode 6 bytes from the start of the sled.
103   // 3. Put the relative offset 7 bytes from the start of the sled.
104   // 4. Do an atomic write over the jmp instruction for the "mov r10d"
105   // opcode and first operand.
106   //
107   // Prerequisite is to compute the relative offset to the trampoline's address.
108   int64_t TrampolineOffset = reinterpret_cast<int64_t>(Trampoline) -
109                              (static_cast<int64_t>(Sled.Address) + 11);
110   if (TrampolineOffset < MinOffset || TrampolineOffset > MaxOffset) {
111     Report("XRay Entry trampoline (%p) too far from sled (%p)\n",
112            Trampoline, reinterpret_cast<void *>(Sled.Address));
113     return false;
114   }
115   if (Enable) {
116     *reinterpret_cast<uint32_t *>(Sled.Address + 2) = FuncId;
117     *reinterpret_cast<uint8_t *>(Sled.Address + 6) = CallOpCode;
118     *reinterpret_cast<uint32_t *>(Sled.Address + 7) = TrampolineOffset;
119     std::atomic_store_explicit(
120         reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), MovR10Seq,
121         std::memory_order_release);
122   } else {
123     std::atomic_store_explicit(
124         reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), Jmp9Seq,
125         std::memory_order_release);
126     // FIXME: Write out the nops still?
127   }
128   return true;
129 }
130
131 bool patchFunctionExit(const bool Enable, const uint32_t FuncId,
132                        const XRaySledEntry &Sled) XRAY_NEVER_INSTRUMENT {
133   // Here we do the dance of replacing the following sled:
134   //
135   // xray_sled_n:
136   //   ret
137   //   <10 byte nop>
138   //
139   // With the following:
140   //
141   //   mov r10d, <function id>
142   //   jmp <relative 32bit offset to exit trampoline>
143   //
144   // 1. Put the function id first, 2 bytes from the start of the sled (just
145   // after the 1-byte ret instruction).
146   // 2. Put the jmp opcode 6 bytes from the start of the sled.
147   // 3. Put the relative offset 7 bytes from the start of the sled.
148   // 4. Do an atomic write over the jmp instruction for the "mov r10d"
149   // opcode and first operand.
150   //
151   // Prerequisite is to compute the relative offset fo the
152   // __xray_FunctionExit function's address.
153   int64_t TrampolineOffset = reinterpret_cast<int64_t>(__xray_FunctionExit) -
154                              (static_cast<int64_t>(Sled.Address) + 11);
155   if (TrampolineOffset < MinOffset || TrampolineOffset > MaxOffset) {
156     Report("XRay Exit trampoline (%p) too far from sled (%p)\n",
157            __xray_FunctionExit, reinterpret_cast<void *>(Sled.Address));
158     return false;
159   }
160   if (Enable) {
161     *reinterpret_cast<uint32_t *>(Sled.Address + 2) = FuncId;
162     *reinterpret_cast<uint8_t *>(Sled.Address + 6) = JmpOpCode;
163     *reinterpret_cast<uint32_t *>(Sled.Address + 7) = TrampolineOffset;
164     std::atomic_store_explicit(
165         reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), MovR10Seq,
166         std::memory_order_release);
167   } else {
168     std::atomic_store_explicit(
169         reinterpret_cast<std::atomic<uint8_t> *>(Sled.Address), RetOpCode,
170         std::memory_order_release);
171     // FIXME: Write out the nops still?
172   }
173   return true;
174 }
175
176 bool patchFunctionTailExit(const bool Enable, const uint32_t FuncId,
177                            const XRaySledEntry &Sled) XRAY_NEVER_INSTRUMENT {
178   // Here we do the dance of replacing the tail call sled with a similar
179   // sequence as the entry sled, but calls the tail exit sled instead.
180   int64_t TrampolineOffset =
181       reinterpret_cast<int64_t>(__xray_FunctionTailExit) -
182       (static_cast<int64_t>(Sled.Address) + 11);
183   if (TrampolineOffset < MinOffset || TrampolineOffset > MaxOffset) {
184     Report("XRay Exit trampoline (%p) too far from sled (%p)\n",
185            __xray_FunctionExit, reinterpret_cast<void *>(Sled.Address));
186     return false;
187   }
188   if (Enable) {
189     *reinterpret_cast<uint32_t *>(Sled.Address + 2) = FuncId;
190     *reinterpret_cast<uint8_t *>(Sled.Address + 6) = CallOpCode;
191     *reinterpret_cast<uint32_t *>(Sled.Address + 7) = TrampolineOffset;
192     std::atomic_store_explicit(
193         reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), MovR10Seq,
194         std::memory_order_release);
195   } else {
196     std::atomic_store_explicit(
197         reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), Jmp9Seq,
198         std::memory_order_release);
199     // FIXME: Write out the nops still?
200   }
201   return true;
202 }
203
204 // We determine whether the CPU we're running on has the correct features we
205 // need. In x86_64 this will be rdtscp support.
206 bool probeRequiredCPUFeatures() XRAY_NEVER_INSTRUMENT {
207   unsigned int EAX, EBX, ECX, EDX;
208
209   // We check whether rdtscp support is enabled. According to the x86_64 manual,
210   // level should be set at 0x80000001, and we should have a look at bit 27 in
211   // EDX. That's 0x8000000 (or 1u << 26).
212   __get_cpuid(0x80000001, &EAX, &EBX, &ECX, &EDX);
213   if (!(EDX & (1u << 26))) {
214     Report("Missing rdtscp support.\n");
215     return false;
216   }
217   // Also check whether we can determine the CPU frequency, since if we cannot,
218   // we should use the emulated TSC instead.
219   if (!getTSCFrequency()) {
220     Report("Unable to determine CPU frequency.\n");
221     return false;
222   }
223   return true;
224 }
225
226 } // namespace __xray