]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/xray/xray_x86_64.cc
Merge ^/head r318658 through r318963.
[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 uint16_t Jmp20Seq = 0x14eb;
79 static constexpr uint8_t JmpOpCode = 0xe9;
80 static constexpr uint8_t RetOpCode = 0xc3;
81 static constexpr uint16_t NopwSeq = 0x9066;
82
83 static constexpr int64_t MinOffset{std::numeric_limits<int32_t>::min()};
84 static constexpr int64_t MaxOffset{std::numeric_limits<int32_t>::max()};
85
86 bool patchFunctionEntry(const bool Enable, const uint32_t FuncId,
87                         const XRaySledEntry &Sled,
88                         void (*Trampoline)()) XRAY_NEVER_INSTRUMENT {
89   // Here we do the dance of replacing the following sled:
90   //
91   // xray_sled_n:
92   //   jmp +9
93   //   <9 byte nop>
94   //
95   // With the following:
96   //
97   //   mov r10d, <function id>
98   //   call <relative 32bit offset to entry trampoline>
99   //
100   // We need to do this in the following order:
101   //
102   // 1. Put the function id first, 2 bytes from the start of the sled (just
103   // after the 2-byte jmp instruction).
104   // 2. Put the call opcode 6 bytes from the start of the sled.
105   // 3. Put the relative offset 7 bytes from the start of the sled.
106   // 4. Do an atomic write over the jmp instruction for the "mov r10d"
107   // opcode and first operand.
108   //
109   // Prerequisite is to compute the relative offset to the trampoline's address.
110   int64_t TrampolineOffset = reinterpret_cast<int64_t>(Trampoline) -
111                              (static_cast<int64_t>(Sled.Address) + 11);
112   if (TrampolineOffset < MinOffset || TrampolineOffset > MaxOffset) {
113     Report("XRay Entry trampoline (%p) too far from sled (%p)\n",
114            Trampoline, reinterpret_cast<void *>(Sled.Address));
115     return false;
116   }
117   if (Enable) {
118     *reinterpret_cast<uint32_t *>(Sled.Address + 2) = FuncId;
119     *reinterpret_cast<uint8_t *>(Sled.Address + 6) = CallOpCode;
120     *reinterpret_cast<uint32_t *>(Sled.Address + 7) = TrampolineOffset;
121     std::atomic_store_explicit(
122         reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), MovR10Seq,
123         std::memory_order_release);
124   } else {
125     std::atomic_store_explicit(
126         reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), Jmp9Seq,
127         std::memory_order_release);
128     // FIXME: Write out the nops still?
129   }
130   return true;
131 }
132
133 bool patchFunctionExit(const bool Enable, const uint32_t FuncId,
134                        const XRaySledEntry &Sled) XRAY_NEVER_INSTRUMENT {
135   // Here we do the dance of replacing the following sled:
136   //
137   // xray_sled_n:
138   //   ret
139   //   <10 byte nop>
140   //
141   // With the following:
142   //
143   //   mov r10d, <function id>
144   //   jmp <relative 32bit offset to exit trampoline>
145   //
146   // 1. Put the function id first, 2 bytes from the start of the sled (just
147   // after the 1-byte ret instruction).
148   // 2. Put the jmp opcode 6 bytes from the start of the sled.
149   // 3. Put the relative offset 7 bytes from the start of the sled.
150   // 4. Do an atomic write over the jmp instruction for the "mov r10d"
151   // opcode and first operand.
152   //
153   // Prerequisite is to compute the relative offset fo the
154   // __xray_FunctionExit function's address.
155   int64_t TrampolineOffset = reinterpret_cast<int64_t>(__xray_FunctionExit) -
156                              (static_cast<int64_t>(Sled.Address) + 11);
157   if (TrampolineOffset < MinOffset || TrampolineOffset > MaxOffset) {
158     Report("XRay Exit trampoline (%p) too far from sled (%p)\n",
159            __xray_FunctionExit, reinterpret_cast<void *>(Sled.Address));
160     return false;
161   }
162   if (Enable) {
163     *reinterpret_cast<uint32_t *>(Sled.Address + 2) = FuncId;
164     *reinterpret_cast<uint8_t *>(Sled.Address + 6) = JmpOpCode;
165     *reinterpret_cast<uint32_t *>(Sled.Address + 7) = TrampolineOffset;
166     std::atomic_store_explicit(
167         reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), MovR10Seq,
168         std::memory_order_release);
169   } else {
170     std::atomic_store_explicit(
171         reinterpret_cast<std::atomic<uint8_t> *>(Sled.Address), RetOpCode,
172         std::memory_order_release);
173     // FIXME: Write out the nops still?
174   }
175   return true;
176 }
177
178 bool patchFunctionTailExit(const bool Enable, const uint32_t FuncId,
179                            const XRaySledEntry &Sled) XRAY_NEVER_INSTRUMENT {
180   // Here we do the dance of replacing the tail call sled with a similar
181   // sequence as the entry sled, but calls the tail exit sled instead.
182   int64_t TrampolineOffset =
183       reinterpret_cast<int64_t>(__xray_FunctionTailExit) -
184       (static_cast<int64_t>(Sled.Address) + 11);
185   if (TrampolineOffset < MinOffset || TrampolineOffset > MaxOffset) {
186     Report("XRay Exit trampoline (%p) too far from sled (%p)\n",
187            __xray_FunctionExit, reinterpret_cast<void *>(Sled.Address));
188     return false;
189   }
190   if (Enable) {
191     *reinterpret_cast<uint32_t *>(Sled.Address + 2) = FuncId;
192     *reinterpret_cast<uint8_t *>(Sled.Address + 6) = CallOpCode;
193     *reinterpret_cast<uint32_t *>(Sled.Address + 7) = TrampolineOffset;
194     std::atomic_store_explicit(
195         reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), MovR10Seq,
196         std::memory_order_release);
197   } else {
198     std::atomic_store_explicit(
199         reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), Jmp9Seq,
200         std::memory_order_release);
201     // FIXME: Write out the nops still?
202   }
203   return true;
204 }
205
206 bool patchCustomEvent(const bool Enable, const uint32_t FuncId,
207                       const XRaySledEntry &Sled) XRAY_NEVER_INSTRUMENT {
208   // Here we do the dance of replacing the following sled:
209   //
210   // xray_sled_n:
211   //   jmp +19          // 2 bytes
212   //   ...
213   //
214   // With the following:
215   //
216   //   nopw             // 2 bytes*
217   //   ...
218   //
219   // We need to do this in the following order:
220   //
221   // 1. Overwrite the 5-byte nop with the call (relative), where (relative) is
222   //    the relative offset to the __xray_CustomEvent trampoline.
223   // 2. Do a two-byte atomic write over the 'jmp +24' to turn it into a 'nopw'.
224   //    This allows us to "enable" this code once the changes have committed.
225   //
226   // The "unpatch" should just turn the 'nopw' back to a 'jmp +24'.
227   //
228   if (Enable) {
229     std::atomic_store_explicit(
230         reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), NopwSeq,
231         std::memory_order_release);
232   } else {
233     std::atomic_store_explicit(
234         reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), Jmp20Seq,
235         std::memory_order_release);
236   }
237   return false;
238 }
239
240 // We determine whether the CPU we're running on has the correct features we
241 // need. In x86_64 this will be rdtscp support.
242 bool probeRequiredCPUFeatures() XRAY_NEVER_INSTRUMENT {
243   unsigned int EAX, EBX, ECX, EDX;
244
245   // We check whether rdtscp support is enabled. According to the x86_64 manual,
246   // level should be set at 0x80000001, and we should have a look at bit 27 in
247   // EDX. That's 0x8000000 (or 1u << 26).
248   __get_cpuid(0x80000001, &EAX, &EBX, &ECX, &EDX);
249   if (!(EDX & (1u << 26))) {
250     Report("Missing rdtscp support.\n");
251     return false;
252   }
253   // Also check whether we can determine the CPU frequency, since if we cannot,
254   // we should use the emulated TSC instead.
255   if (!getTSCFrequency()) {
256     Report("Unable to determine CPU frequency.\n");
257     return false;
258   }
259   return true;
260 }
261
262 } // namespace __xray