]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/xray/xray_interface.cc
Merge ^/head r317971 through r318379.
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / xray / xray_interface.cc
1 //===-- xray_interface.cpp --------------------------------------*- 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 // Implementation of the API functions.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "xray_interface_internal.h"
17
18 #include <cstdint>
19 #include <cstdio>
20 #include <errno.h>
21 #include <limits>
22 #include <sys/mman.h>
23
24 #include "sanitizer_common/sanitizer_common.h"
25 #include "xray_defs.h"
26
27 namespace __xray {
28
29 #if defined(__x86_64__)
30 // FIXME: The actual length is 11 bytes. Why was length 12 passed to mprotect()
31 // ?
32 static const int16_t cSledLength = 12;
33 #elif defined(__aarch64__)
34 static const int16_t cSledLength = 32;
35 #elif defined(__arm__)
36 static const int16_t cSledLength = 28;
37 #elif SANITIZER_MIPS32
38 static const int16_t cSledLength = 48;
39 #elif SANITIZER_MIPS64
40 static const int16_t cSledLength = 64;
41 #elif defined(__powerpc64__)
42 static const int16_t cSledLength = 8;
43 #else
44 #error "Unsupported CPU Architecture"
45 #endif /* CPU architecture */
46
47 // This is the function to call when we encounter the entry or exit sleds.
48 __sanitizer::atomic_uintptr_t XRayPatchedFunction{0};
49
50 // This is the function to call from the arg1-enabled sleds/trampolines.
51 __sanitizer::atomic_uintptr_t XRayArgLogger{0};
52
53 // MProtectHelper is an RAII wrapper for calls to mprotect(...) that will undo
54 // any successful mprotect(...) changes. This is used to make a page writeable
55 // and executable, and upon destruction if it was successful in doing so returns
56 // the page into a read-only and executable page.
57 //
58 // This is only used specifically for runtime-patching of the XRay
59 // instrumentation points. This assumes that the executable pages are originally
60 // read-and-execute only.
61 class MProtectHelper {
62   void *PageAlignedAddr;
63   std::size_t MProtectLen;
64   bool MustCleanup;
65
66 public:
67   explicit MProtectHelper(void *PageAlignedAddr,
68                           std::size_t MProtectLen) XRAY_NEVER_INSTRUMENT
69       : PageAlignedAddr(PageAlignedAddr),
70         MProtectLen(MProtectLen),
71         MustCleanup(false) {}
72
73   int MakeWriteable() XRAY_NEVER_INSTRUMENT {
74     auto R = mprotect(PageAlignedAddr, MProtectLen,
75                       PROT_READ | PROT_WRITE | PROT_EXEC);
76     if (R != -1)
77       MustCleanup = true;
78     return R;
79   }
80
81   ~MProtectHelper() XRAY_NEVER_INSTRUMENT {
82     if (MustCleanup) {
83       mprotect(PageAlignedAddr, MProtectLen, PROT_READ | PROT_EXEC);
84     }
85   }
86 };
87
88 } // namespace __xray
89
90 extern __sanitizer::SpinMutex XRayInstrMapMutex;
91 extern __sanitizer::atomic_uint8_t XRayInitialized;
92 extern __xray::XRaySledMap XRayInstrMap;
93
94 int __xray_set_handler(void (*entry)(int32_t,
95                                      XRayEntryType)) XRAY_NEVER_INSTRUMENT {
96   if (__sanitizer::atomic_load(&XRayInitialized,
97                                __sanitizer::memory_order_acquire)) {
98
99     __sanitizer::atomic_store(&__xray::XRayPatchedFunction,
100                               reinterpret_cast<uint64_t>(entry),
101                               __sanitizer::memory_order_release);
102     return 1;
103   }
104   return 0;
105 }
106
107 int __xray_remove_handler() XRAY_NEVER_INSTRUMENT {
108   return __xray_set_handler(nullptr);
109 }
110
111 __sanitizer::atomic_uint8_t XRayPatching{0};
112
113 using namespace __xray;
114
115 // FIXME: Figure out whether we can move this class to sanitizer_common instead
116 // as a generic "scope guard".
117 template <class Function> class CleanupInvoker {
118   Function Fn;
119
120 public:
121   explicit CleanupInvoker(Function Fn) XRAY_NEVER_INSTRUMENT : Fn(Fn) {}
122   CleanupInvoker(const CleanupInvoker &) XRAY_NEVER_INSTRUMENT = default;
123   CleanupInvoker(CleanupInvoker &&) XRAY_NEVER_INSTRUMENT = default;
124   CleanupInvoker &
125   operator=(const CleanupInvoker &) XRAY_NEVER_INSTRUMENT = delete;
126   CleanupInvoker &operator=(CleanupInvoker &&) XRAY_NEVER_INSTRUMENT = delete;
127   ~CleanupInvoker() XRAY_NEVER_INSTRUMENT { Fn(); }
128 };
129
130 template <class Function>
131 CleanupInvoker<Function> scopeCleanup(Function Fn) XRAY_NEVER_INSTRUMENT {
132   return CleanupInvoker<Function>{Fn};
133 }
134
135 inline bool patchSled(const XRaySledEntry &Sled, bool Enable,
136                       int32_t FuncId) XRAY_NEVER_INSTRUMENT {
137   // While we're here, we should patch the nop sled. To do that we mprotect
138   // the page containing the function to be writeable.
139   const uint64_t PageSize = GetPageSizeCached();
140   void *PageAlignedAddr =
141       reinterpret_cast<void *>(Sled.Address & ~(PageSize - 1));
142   std::size_t MProtectLen = (Sled.Address + cSledLength) -
143                             reinterpret_cast<uint64_t>(PageAlignedAddr);
144   MProtectHelper Protector(PageAlignedAddr, MProtectLen);
145   if (Protector.MakeWriteable() == -1) {
146     printf("Failed mprotect: %d\n", errno);
147     return XRayPatchingStatus::FAILED;
148   }
149
150   bool Success = false;
151   switch (Sled.Kind) {
152   case XRayEntryType::ENTRY:
153     Success = patchFunctionEntry(Enable, FuncId, Sled, __xray_FunctionEntry);
154     break;
155   case XRayEntryType::EXIT:
156     Success = patchFunctionExit(Enable, FuncId, Sled);
157     break;
158   case XRayEntryType::TAIL:
159     Success = patchFunctionTailExit(Enable, FuncId, Sled);
160     break;
161   case XRayEntryType::LOG_ARGS_ENTRY:
162     Success = patchFunctionEntry(Enable, FuncId, Sled, __xray_ArgLoggerEntry);
163     break;
164   default:
165     Report("Unsupported sled kind '%d' @%04x\n", Sled.Address, int(Sled.Kind));
166     return false;
167   }
168   return Success;
169 }
170
171 // controlPatching implements the common internals of the patching/unpatching
172 // implementation. |Enable| defines whether we're enabling or disabling the
173 // runtime XRay instrumentation.
174 XRayPatchingStatus controlPatching(bool Enable) XRAY_NEVER_INSTRUMENT {
175   if (!__sanitizer::atomic_load(&XRayInitialized,
176                                 __sanitizer::memory_order_acquire))
177     return XRayPatchingStatus::NOT_INITIALIZED; // Not initialized.
178
179   uint8_t NotPatching = false;
180   if (!__sanitizer::atomic_compare_exchange_strong(
181           &XRayPatching, &NotPatching, true, __sanitizer::memory_order_acq_rel))
182     return XRayPatchingStatus::ONGOING; // Already patching.
183
184   uint8_t PatchingSuccess = false;
185   auto XRayPatchingStatusResetter = scopeCleanup([&PatchingSuccess] {
186     if (!PatchingSuccess)
187       __sanitizer::atomic_store(&XRayPatching, false,
188                                 __sanitizer::memory_order_release);
189   });
190
191   // Step 1: Compute the function id, as a unique identifier per function in the
192   // instrumentation map.
193   XRaySledMap InstrMap;
194   {
195     __sanitizer::SpinMutexLock Guard(&XRayInstrMapMutex);
196     InstrMap = XRayInstrMap;
197   }
198   if (InstrMap.Entries == 0)
199     return XRayPatchingStatus::NOT_INITIALIZED;
200
201   const uint64_t PageSize = GetPageSizeCached();
202   if ((PageSize == 0) || ((PageSize & (PageSize - 1)) != 0)) {
203     Report("System page size is not a power of two: %lld\n", PageSize);
204     return XRayPatchingStatus::FAILED;
205   }
206
207   uint32_t FuncId = 1;
208   uint64_t CurFun = 0;
209   for (std::size_t I = 0; I < InstrMap.Entries; I++) {
210     auto Sled = InstrMap.Sleds[I];
211     auto F = Sled.Function;
212     if (CurFun == 0)
213       CurFun = F;
214     if (F != CurFun) {
215       ++FuncId;
216       CurFun = F;
217     }
218     patchSled(Sled, Enable, FuncId);
219   }
220   __sanitizer::atomic_store(&XRayPatching, false,
221                             __sanitizer::memory_order_release);
222   PatchingSuccess = true;
223   return XRayPatchingStatus::SUCCESS;
224 }
225
226 XRayPatchingStatus __xray_patch() XRAY_NEVER_INSTRUMENT {
227   return controlPatching(true);
228 }
229
230 XRayPatchingStatus __xray_unpatch() XRAY_NEVER_INSTRUMENT {
231   return controlPatching(false);
232 }
233
234 XRayPatchingStatus patchFunction(int32_t FuncId,
235                                  bool Enable) XRAY_NEVER_INSTRUMENT {
236   if (!__sanitizer::atomic_load(&XRayInitialized,
237                                 __sanitizer::memory_order_acquire))
238     return XRayPatchingStatus::NOT_INITIALIZED; // Not initialized.
239
240   uint8_t NotPatching = false;
241   if (!__sanitizer::atomic_compare_exchange_strong(
242           &XRayPatching, &NotPatching, true, __sanitizer::memory_order_acq_rel))
243     return XRayPatchingStatus::ONGOING; // Already patching.
244
245   // Next, we look for the function index.
246   XRaySledMap InstrMap;
247   {
248     __sanitizer::SpinMutexLock Guard(&XRayInstrMapMutex);
249     InstrMap = XRayInstrMap;
250   }
251
252   // If we don't have an index, we can't patch individual functions.
253   if (InstrMap.Functions == 0)
254     return XRayPatchingStatus::NOT_INITIALIZED;
255
256   // FuncId must be a positive number, less than the number of functions
257   // instrumented.
258   if (FuncId <= 0 || static_cast<size_t>(FuncId) > InstrMap.Functions) {
259     Report("Invalid function id provided: %d\n", FuncId);
260     return XRayPatchingStatus::FAILED;
261   }
262
263   // Now we patch ths sleds for this specific function.
264   auto SledRange = InstrMap.SledsIndex[FuncId - 1];
265   auto *f = SledRange.Begin;
266   auto *e = SledRange.End;
267
268   bool SucceedOnce = false;
269   while (f != e)
270     SucceedOnce |= patchSled(*f++, Enable, FuncId);
271
272   __sanitizer::atomic_store(&XRayPatching, false,
273                             __sanitizer::memory_order_release);
274
275   if (!SucceedOnce) {
276     Report("Failed patching any sled for function '%d'.", FuncId);
277     return XRayPatchingStatus::FAILED;
278   }
279
280   return XRayPatchingStatus::SUCCESS;
281 }
282
283 XRayPatchingStatus __xray_patch_function(int32_t FuncId) XRAY_NEVER_INSTRUMENT {
284   return patchFunction(FuncId, true);
285 }
286
287 XRayPatchingStatus
288 __xray_unpatch_function(int32_t FuncId) XRAY_NEVER_INSTRUMENT {
289   return patchFunction(FuncId, false);
290 }
291
292 int __xray_set_handler_arg1(void (*Handler)(int32_t, XRayEntryType, uint64_t)) {
293   if (!__sanitizer::atomic_load(&XRayInitialized,
294                                 __sanitizer::memory_order_acquire))
295     return 0;
296
297   // A relaxed write might not be visible even if the current thread gets
298   // scheduled on a different CPU/NUMA node.  We need to wait for everyone to
299   // have this handler installed for consistency of collected data across CPUs.
300   __sanitizer::atomic_store(&XRayArgLogger, reinterpret_cast<uint64_t>(Handler),
301                             __sanitizer::memory_order_release);
302   return 1;
303 }
304 int __xray_remove_handler_arg1() { return __xray_set_handler_arg1(nullptr); }
305
306 uintptr_t __xray_function_address(int32_t FuncId) XRAY_NEVER_INSTRUMENT {
307   __sanitizer::SpinMutexLock Guard(&XRayInstrMapMutex);
308   if (FuncId <= 0 || static_cast<size_t>(FuncId) > XRayInstrMap.Functions)
309     return 0;
310   return XRayInstrMap.SledsIndex[FuncId - 1].Begin->Address;
311 }
312
313 size_t __xray_max_function_id() XRAY_NEVER_INSTRUMENT {
314   __sanitizer::SpinMutexLock Guard(&XRayInstrMapMutex);
315   return XRayInstrMap.Functions;
316 }